diff --git a/package.json b/package.json index 7005105..9b3a9e2 100644 --- a/package.json +++ b/package.json @@ -9,87 +9,86 @@ "scripts": { "build": "rimraf -rf dist/ && tsc", "test": "cross-env NODE_ENV=development cross-env TEST_MODE=true nyc mocha --exit", - "check": "echo \"Checking...\" && tsc && npm run tslint", + "check": "echo \"Checking...\" && tsc && npm run lint", "dev": "cross-env NODE_ENV=development nodemon --watch scripts --watch dist dist/scripts/dev.js", "create-db": "cross-env NODE_ENV=development node dist/scripts/init", - "tslint": "tslint -c tslint.json -p tsconfig.json", "start": "cross-env NODE_ENV=production pm2 start dist/dispatch.js --name=rap-server-delos", + "lint": "echo \"TSLint checking...\" && tslint -c tslint.json 'src/**/*.ts' 'src/**/*.tsx'", "start:redis": "pm2 start redis-server --name redis-server", "clean": "pm2 delete all" }, "author": "bosn, nuysoft", "license": "ISC", "dependencies": { - "chalk": "^2.4.1", - "cluster": "^0.7.7", - "cross-env": "^5.1.1", - "graceful": "^1.0.1", - "ioredis": "^3.2.2", + "chalk": "^2.4.2", + "cross-env": "^5.2.0", + "graceful": "^1.0.2", "is-md5": "^0.0.2", - "js-beautify": "^1.6.9", - "kcors": "^2.2.1", - "koa": "^2.2.0", - "koa-body": "^4.0.1", + "js-beautify": "^1.10.0", + "kcors": "^2.2.2", + "koa": "^2.7.0", + "koa-body": "^4.1.0", "koa-generic-session": "^2.0.1", "koa-logger": "^3.2.0", - "koa-redis": "^3.1.2", - "koa-router": "^7.1.1", - "koa-send": "^4.0.0", - "koa-static": "^4.0.2", - "md5": "^2.2.1", + "koa-redis": "^4.0.0", + "koa-router": "^7.4.0", + "koa-send": "^5.0.0", + "koa-static": "^5.0.0", "lodash": "^4.17.11", + "md5": "^2.2.1", "mockjs": "^1.0.1-beta3", - "moment": "^2.17.1", - "mysql": "^2.11.1", - "mysql2": "^1.5.1", - "node-fetch": "^2.1.2", + "moment": "^2.24.0", + "mysql": "^2.17.1", + "mysql2": "^1.6.5", + "node-fetch": "^2.6.0", "node-print": "0.0.4", - "nodemailer": "^4.6.8", - "notevil": "^1.1.0", - "path-to-regexp": "^2.2.1", + "nodemailer": "^6.2.1", + "notevil": "^1.3.1", + "path-to-regexp": "^3.0.0", "redis": "^2.8.0", - "reflect-metadata": "^0.1.10", - "request": "^2.85.0", - "request-promise": "^4.2.2", - "sequelize": "^4.28.6", - "sequelize-typescript": "^0.6.4", - "svg-captcha": "^1.3.11", - "underscore": "^1.8.3", - "urllib": "^2.28.1" + "reflect-metadata": "^0.1.13", + "request": "^2.88.0", + "request-promise": "^4.2.4", + "sequelize": "^5.8.7", + "sequelize-typescript": "^1.0.0-beta.3", + "svg-captcha": "^1.4.0", + "underscore": "^1.9.1", + "urllib": "^2.34.0" }, "devDependencies": { - "@types/chai": "^4.0.10", - "@types/kcors": "^2.2.2", - "@types/koa": "^2.0.43", + "@ali/keycenter": "^1.0.2", + "@ali/oplog": "^1.0.1", + "@types/chai": "^4.1.7", + "@types/kcors": "^2.2.3", + "@types/koa": "^2.0.48", "@types/koa-generic-session": "^1.0.2", - "@types/koa-logger": "^3.1.0", + "@types/koa-logger": "^3.1.1", "@types/koa-redis": "^3.0.2", - "@types/koa-router": "^7.0.27", - "@types/koa-static": "^4.0.0", - "@types/lodash": "^4.14.106", - "@types/md5": "^2.1.32", - "@types/mocha": "^5.2.0", - "@types/mockjs": "^1.0.0", - "@types/node": "^10.1.0", - "@types/nodemailer": "^4.6.5", - "@types/redis": "^2.8.6", - "@types/request": "^2.47.0", - "@types/request-promise": "^4.1.41", - "@types/sequelize": "^4.27.12", - "@types/underscore": "^1.8.8", - "babel-eslint": "^8.2.3", - "chai": "^4.1.2", - "mocha": "^5.1.1", - "nodemon": "^1.11.0", - "npm-run-all": "^4.0.2", - "nyc": "^12.0.2", + "@types/koa-router": "^7.0.40", + "@types/koa-static": "^4.0.1", + "@types/lodash": "^4.14.132", + "@types/md5": "^2.1.33", + "@types/mocha": "^5.2.6", + "@types/mockjs": "^1.0.2", + "@types/node": "^12.0.3", + "@types/nodemailer": "^6.2.0", + "@types/redis": "^2.8.13", + "@types/request": "^2.48.1", + "@types/request-promise": "^4.1.44", + "@types/underscore": "^1.8.18", + "babel-eslint": "^10.0.1", + "chai": "^4.2.0", + "mocha": "^6.1.4", + "nodemon": "^1.19.1", + "npm-run-all": "^4.1.5", + "nyc": "^14.1.1", "pre-commit": "^1.2.2", - "rimraf": "^2.6.2", - "source-map-support": "^0.5.0", - "standard": "^11.0.1", - "supertest": "^3.0.0", - "tslint": "^5.8.0", - "typescript": "^2.9.2" + "rimraf": "^2.6.3", + "source-map-support": "^0.5.12", + "standard": "^12.0.1", + "supertest": "^4.0.2", + "tslint": "^5.16.0", + "typescript": "^3.5.1" }, "pre-commit": [ "check" diff --git a/src/config/config.dev.ts b/src/config/config.dev.ts index 1363a09..ecf5fa9 100644 --- a/src/config/config.dev.ts +++ b/src/config/config.dev.ts @@ -1,4 +1,4 @@ -import { IConfigOptions } from "../types"; +import { IConfigOptions } from "../types" let config: IConfigOptions = { version: '2.3', @@ -30,7 +30,7 @@ let config: IConfigOptions = { secure: false, auth: { user: 'rap2_notify@outlook.com', - pass: '' + pass: 'P}6}Rp?J83mB3pm2wXtNLBECPX,qDyEnEW[' } }, mailSender: 'rap2_notify@outlook.com', diff --git a/src/config/config.local.ts b/src/config/config.local.ts index d37a4ba..9770770 100644 --- a/src/config/config.local.ts +++ b/src/config/config.local.ts @@ -1,4 +1,4 @@ -import { IConfigOptions } from "../types"; +import { IConfigOptions } from "../types" let config: IConfigOptions = { version: '2.3', diff --git a/src/config/config.prod.ts b/src/config/config.prod.ts index cfeaee8..970c594 100644 --- a/src/config/config.prod.ts +++ b/src/config/config.prod.ts @@ -1,4 +1,4 @@ -import { IConfigOptions } from "../types"; +import { IConfigOptions } from "../types" // 先从环境变量取配置 let config: IConfigOptions = { @@ -35,10 +35,10 @@ let config: IConfigOptions = { secure: false, auth: { user: 'rap2_notify@outlook.com', - pass: '' + pass: 'P}6}Rp?J83mB3pm2wXtNLBECPX,qDyEnEW[' } }, mailSender: 'rap2_notify@outlook.com', } -export default config +export default config \ No newline at end of file diff --git a/src/config/index.ts b/src/config/index.ts index 7898df5..2b879b3 100644 --- a/src/config/index.ts +++ b/src/config/index.ts @@ -1,4 +1,4 @@ -import { IConfigOptions } from "../types"; +import { IConfigOptions } from "../types" // local or development or production let configObj: IConfigOptions = diff --git a/src/models/bo/interface.ts b/src/models/bo/interface.ts index c4de8b9..6b3e914 100644 --- a/src/models/bo/interface.ts +++ b/src/models/bo/interface.ts @@ -1,5 +1,5 @@ -import { Table, Column, Model, HasMany, AutoIncrement, PrimaryKey, AllowNull, DataType, Default, BelongsTo, ForeignKey, BeforeBulkDelete, BeforeBulkCreate, BeforeBulkUpdate, BeforeCreate, BeforeUpdate, BeforeDelete } from 'sequelize-typescript' -import { User, Module, Repository, Property } from '../'; +import { Table, Column, Model, HasMany, AutoIncrement, PrimaryKey, AllowNull, DataType, Default, BelongsTo, ForeignKey, BeforeBulkDestroy, BeforeBulkCreate, BeforeBulkUpdate, BeforeCreate, BeforeUpdate, BeforeDestroy } from 'sequelize-typescript' +import { User, Module, Repository, Property } from '../' import RedisService, { CACHE_KEY } from '../../service/redis' import * as Sequelize from 'sequelize' @@ -13,16 +13,16 @@ export default class Interface extends Model { /** hooks */ @BeforeCreate @BeforeUpdate - @BeforeDelete + @BeforeDestroy static async deleteCache(instance: Interface) { await RedisService.delCache(CACHE_KEY.REPOSITORY_GET, instance.repositoryId) } @BeforeBulkCreate @BeforeBulkUpdate - @BeforeBulkDelete + @BeforeBulkDestroy static async bulkDeleteCache(options: any) { - let id: number = +(options && options.attributes && options.attributes.id) + let id: number = options && options.rawAttributes && options.rawAttributes.id if (!id) { id = options.where && +options.where.id } @@ -32,9 +32,8 @@ export default class Interface extends Model { id = arr[1].id } } - if (+id) { - id = +id - const itf = await Interface.findById(id) + if (id) { + const itf = await Interface.findByPk(id) await RedisService.delCache(CACHE_KEY.REPOSITORY_GET, itf.repositoryId) } } @@ -66,7 +65,7 @@ export default class Interface extends Model { @AllowNull(false) @Default(1) - @Column(DataType.BIGINT(11)) + @Column(DataType.BIGINT()) priority: number @Default(200) diff --git a/src/models/bo/module.ts b/src/models/bo/module.ts index 66c0c1a..e319eb8 100644 --- a/src/models/bo/module.ts +++ b/src/models/bo/module.ts @@ -1,27 +1,27 @@ -import { Table, Column, Model, HasMany, AutoIncrement, PrimaryKey, AllowNull, DataType, Default, BelongsTo, ForeignKey, BeforeCreate, BeforeUpdate, BeforeDelete, BeforeBulkCreate, BeforeBulkDelete, BeforeBulkUpdate } from 'sequelize-typescript' +import { Table, Column, Model, HasMany, AutoIncrement, PrimaryKey, AllowNull, DataType, Default, BelongsTo, ForeignKey, BeforeCreate, BeforeUpdate, BeforeDestroy, BeforeBulkCreate, BeforeBulkDestroy, BeforeBulkUpdate } from 'sequelize-typescript' import { User, Repository, Interface } from '../' -import RedisService, { CACHE_KEY } from '../../service/redis'; +import RedisService, { CACHE_KEY } from '../../service/redis' @Table({ paranoid: true, freezeTableName: false, timestamps: true }) export default class Module extends Model { /** hooks */ @BeforeCreate @BeforeUpdate - @BeforeDelete + @BeforeDestroy static async deleteCache(instance: Interface) { await RedisService.delCache(CACHE_KEY.REPOSITORY_GET, instance.repositoryId) } @BeforeBulkCreate @BeforeBulkUpdate - @BeforeBulkDelete + @BeforeBulkDestroy static async bulkDeleteCache(options: any) { - let id: number = options && options.attributes && options.attributes.id + let id: number = options && options.rawAttributes && options.rawAttributes.id if (!id) { id = options.where && +options.where.id } if (id) { - const mod = await Module.findById(id) + const mod = await Module.findByPk(id) await RedisService.delCache(CACHE_KEY.REPOSITORY_GET, mod.repositoryId) } } @@ -42,7 +42,7 @@ export default class Module extends Model { @AllowNull(false) @Default(1) - @Column(DataType.BIGINT(11)) + @Column(DataType.BIGINT()) priority: number @ForeignKey(() => User) diff --git a/src/models/bo/property.ts b/src/models/bo/property.ts index 0207873..92248d5 100644 --- a/src/models/bo/property.ts +++ b/src/models/bo/property.ts @@ -20,7 +20,7 @@ export default class Property extends Model { @Column id: number - static attributes: any; + static attributes: any @AllowNull(false) @@ -65,7 +65,7 @@ export default class Property extends Model { @AllowNull(false) @Default(1) - @Column(DataType.BIGINT(11)) + @Column(DataType.BIGINT()) priority: number @ForeignKey(() => Interface) diff --git a/src/models/bo/repository.ts b/src/models/bo/repository.ts index 9f3ec75..3f8ab45 100644 --- a/src/models/bo/repository.ts +++ b/src/models/bo/repository.ts @@ -1,4 +1,4 @@ -import { Table, Column, Model, HasMany, AutoIncrement, PrimaryKey, AllowNull, DataType, Default, BelongsTo, BelongsToMany, ForeignKey, BeforeUpdate, BeforeCreate, BeforeDelete, BeforeBulkCreate, BeforeBulkUpdate, BeforeBulkDelete } from 'sequelize-typescript' +import { Table, Column, Model, HasMany, AutoIncrement, PrimaryKey, AllowNull, DataType, Default, BelongsTo, BelongsToMany, ForeignKey, BeforeUpdate, BeforeCreate, BeforeDestroy, BeforeBulkCreate, BeforeBulkUpdate, BeforeBulkDestroy } from 'sequelize-typescript' import { User, Organization, Module, Interface, RepositoriesCollaborators } from '../' import RedisService, { CACHE_KEY } from '../../service/redis' @@ -8,16 +8,16 @@ export default class Repository extends Model { /** hooks */ @BeforeCreate @BeforeUpdate - @BeforeDelete + @BeforeDestroy static async cleanCache(instance: Repository) { await RedisService.delCache(CACHE_KEY.REPOSITORY_GET, instance.id) } @BeforeBulkCreate @BeforeBulkUpdate - @BeforeBulkDelete + @BeforeBulkDestroy static async bulkDeleteCache(options: any) { - const id = options && options.attributes && options.attributes.id + const id = options && options.rawAttributes && options.rawAttributes.id if (id) { await RedisService.delCache(CACHE_KEY.REPOSITORY_GET, id) } diff --git a/src/models/util/queryInclude.ts b/src/models/util/queryInclude.ts index a8bfcc8..c40f483 100644 --- a/src/models/util/queryInclude.ts +++ b/src/models/util/queryInclude.ts @@ -1,15 +1,15 @@ // TODO 2.2 如何缓存重复查询?https://github.com/rfink/sequelize-redis-cache import { Helper } from './helper' -import User from '../bo/user'; -import Repository from '../bo/repository'; -import Module from '../bo/module'; -import Organization from '../bo/organization'; -import Interface from '../bo/interface'; -import Property from '../bo/property'; -import { Model, IIncludeOptions } from 'sequelize-typescript'; +import User from '../bo/user' +import Repository from '../bo/repository' +import Module from '../bo/module' +import Organization from '../bo/organization' +import Interface from '../bo/interface' +import Property from '../bo/property' +import { IncludeOptions } from 'sequelize' declare interface IQueryInclude { - [key: string]: typeof Model | IIncludeOptions + [key: string]: IncludeOptions } const QueryInclude: IQueryInclude = { diff --git a/src/routes/account.ts b/src/routes/account.ts index 3bad1d8..dde69f5 100644 --- a/src/routes/account.ts +++ b/src/routes/account.ts @@ -1,12 +1,15 @@ import * as svgCaptcha from 'svg-captcha' import { User, Notification, Logger, Organization, Repository } from '../models' import router from './router' -import { Model, Sequelize } from 'sequelize-typescript'; +import { Model } from 'sequelize-typescript' import Pagination from './utils/pagination' import { QueryInclude } from '../models' -import * as md5 from 'md5' +import { Op } from 'sequelize' import MailService from '../service/mail' -const Op = Sequelize.Op +import * as md5 from 'md5' + + + router.get('/app/get', async (ctx, next) => { let data: any = {} @@ -16,8 +19,8 @@ router.get('/app/get', async (ctx, next) => { } for (let name in hooks) { if (!query[name]) continue - data[name] = await hooks[name].findById(query[name], { - attributes: { exclude: [] }, + data[name] = await hooks[name].findByPk(query[name], { + attributes: { exclude: [] } }) } ctx.body = { @@ -61,9 +64,9 @@ router.get('/account/list', async (ctx) => { router.get('/account/info', async (ctx) => { ctx.body = { - data: ctx.session.id ? await User.findById(ctx.session.id, { - attributes: QueryInclude.User.attributes, - }) : undefined, + data: ctx.session.id ? await User.findByPk(ctx.session.id, { + attributes: QueryInclude.User.attributes + }) : undefined } }) @@ -154,7 +157,7 @@ router.post('/account/update', async (ctx) => { } else if (password.length < 6) { errMsg = '密码长度过短' } else { - const user = await User.findById(ctx.session.id) + const user = await User.findByPk(ctx.session.id) user.password = md5(md5(password)) await user.save() isOk = true @@ -244,7 +247,7 @@ router.get('/account/logger', async (ctx) => { } return } - let auth = await User.findById(ctx.session.id) + let auth = await User.findByPk(ctx.session.id) let repositories: Model[] = [...([]>await auth.$get('ownedRepositories')), ...([]>await auth.$get('joinedRepositories'))] let organizations: Model[] = [...([]>await auth.$get('ownedOrganizations')), ...([]>await auth.$get('joinedOrganizations'))] diff --git a/src/routes/analytics.ts b/src/routes/analytics.ts index 64413cb..36cc372 100644 --- a/src/routes/analytics.ts +++ b/src/routes/analytics.ts @@ -1,7 +1,7 @@ import router from './router' -import Repository from "../models/bo/repository"; -import Logger from "../models/bo/logger"; -import User from "../models/bo/user"; +import Repository from "../models/bo/repository" +import Logger from "../models/bo/logger" +import User from "../models/bo/user" const moment = require('moment') const Sequelize = require('sequelize') const SELECT = { type: Sequelize.QueryTypes.SELECT } @@ -23,7 +23,7 @@ router.get('/app/analytics/repositories/created', async (ctx) => { GROUP BY label ORDER BY label ASC; ` - let result = await sequelize.query(sql, SELECT) + let result: any = await sequelize.query(sql, SELECT) result = result.map((item: any) => ({ label: moment(item.label).format(YYYY_MM_DD), value: item.value, @@ -48,7 +48,7 @@ router.get('/app/analytics/repositories/updated', async (ctx) => { GROUP BY label ORDER BY label ASC; ` - let result = await sequelize.query(sql, SELECT) + let result: any = await sequelize.query(sql, SELECT) result = result.map((item: any) => ({ label: moment(item.label).format(YYYY_MM_DD), value: item.value, diff --git a/src/routes/mock.ts b/src/routes/mock.ts index e101329..26f71b7 100644 --- a/src/routes/mock.ts +++ b/src/routes/mock.ts @@ -1,16 +1,15 @@ import router from './router' import { Repository, Interface, Property } from '../models' -import { QueryInclude } from '../models'; +import { QueryInclude } from '../models' import Tree from './utils/tree' import urlUtils from './utils/url' import * as querystring from 'querystring' -import { Sequelize } from 'sequelize-typescript'; import * as urlPkg from 'url' +import { Op } from 'sequelize' const attributes: any = { exclude: [] } const pt = require('node-print').pt const beautify = require('js-beautify').js_beautify -const Op = Sequelize.Op // 检测是否存在重复接口,会在返回的插件 JS 中提示。同时也会在编辑器中提示。 const parseDuplicatedInterfaces = (repository: Repository) => { @@ -65,7 +64,7 @@ router.get('/app/plugin/:repositories', async (ctx) => { let repositoryIds = new Set(ctx.params.repositories.split(',').map((item: string) => +item).filter((item: any) => item)) // _.uniq() => Set let result = [] for (let id of repositoryIds) { - let repository = await Repository.findById(id, { + let repository = await Repository.findByPk(id, { attributes: { exclude: [] }, include: [ QueryInclude.Creator, @@ -136,7 +135,7 @@ router.all('/app/mock/:repositoryId(\\d+)/:url(.+)', async (ctx) => { // KISSY 1.3.2 会把路径中的 // 替换为 /。在浏览器端拦截跨域请求时,需要 encodeURIComponent(url) 以防止 http:// 被替换为 http:/。但是同时也会把参数一起编码,导致 route 的 url 部分包含了参数。 // 所以这里重新解析一遍!!! - let repository = await Repository.findById(repositoryId) + let repository = await Repository.findByPk(repositoryId) let collaborators: Repository[] = (await repository.$get('collaborators')) as Repository[] let itf: Interface @@ -233,12 +232,12 @@ router.all('/app/mock/:repositoryId(\\d+)/:url(.+)', async (ctx) => { ctx.body = { isOk: false, errMsg: '未匹配到任何接口 No matched interface' } return } else { - itf = await Interface.findById(listMatched[0].id) + itf = await Interface.findByPk(listMatched[0].id) } } let interfaceId = itf.id - let properties = await Property.findAll({ + let properties: any = await Property.findAll({ attributes, where: { interfaceId, scope: 'response' }, }) @@ -268,14 +267,14 @@ router.all('/app/mock/:repositoryId(\\d+)/:url(.+)', async (ctx) => { } } - properties = properties.map(item => item.toJSON()) + properties = properties.map((item: any) => item.toJSON()) // DONE 2.2 支持引用请求参数 - let requestProperties = await Property.findAll({ + let requestProperties: any = await Property.findAll({ attributes, where: { interfaceId, scope: 'request' }, }) - requestProperties = requestProperties.map(item => item.toJSON()) + requestProperties = requestProperties.map((item: any) => item.toJSON()) let requestData = Tree.ArrayToTreeToTemplateToData(requestProperties) Object.assign(requestData, ctx.query) const data = Tree.ArrayToTreeToTemplateToData(properties, requestData) @@ -316,19 +315,19 @@ router.get('/app/mock/data/:interfaceId', async (ctx) => { app.counter.mock++ let { interfaceId } = ctx.params let { scope = 'response' } = ctx.query - let properties = await Property.findAll({ + let properties: any = await Property.findAll({ attributes, where: { interfaceId, scope }, }) - properties = properties.map(item => item.toJSON()) + properties = properties.map((item: any) => item.toJSON()) // pt(properties) // DONE 2.2 支持引用请求参数 - let requestProperties = await Property.findAll({ + let requestProperties: any = await Property.findAll({ attributes, where: { interfaceId, scope: 'request' }, }) - requestProperties = requestProperties.map(item => item.toJSON()) + requestProperties = requestProperties.map((item: any) => item.toJSON()) let requestData = Tree.ArrayToTreeToTemplateToData(requestProperties) Object.assign(requestData, ctx.query) @@ -345,12 +344,12 @@ router.get('/app/mock/schema/:interfaceId', async (ctx) => { app.counter.mock++ let { interfaceId } = ctx.params let { scope = 'response' } = ctx.query - let properties = await Property.findAll({ + let properties: any = await Property.findAll({ attributes, where: { interfaceId, scope }, }) - pt(properties.map(item => item.toJSON())) - properties = properties.map(item => item.toJSON()) + pt(properties.map((item: any) => item.toJSON())) + properties = properties.map((item: any) => item.toJSON()) let schema = Tree.ArrayToTreeToTemplateToJSONSchema(properties) ctx.type = 'json' ctx.body = Tree.stringifyWithFunctonAndRegExp(schema) @@ -361,12 +360,12 @@ router.get('/app/mock/tree/:interfaceId', async (ctx) => { app.counter.mock++ let { interfaceId } = ctx.params let { scope = 'response' } = ctx.query - let properties = await Property.findAll({ + let properties: any = await Property.findAll({ attributes, where: { interfaceId, scope }, }) - pt(properties.map(item => item.toJSON())) - properties = properties.map(item => item.toJSON()) + pt(properties.map((item: any) => item.toJSON())) + properties = properties.map((item: any) => item.toJSON()) let tree = Tree.ArrayToTree(properties) ctx.type = 'json' ctx.body = Tree.stringifyWithFunctonAndRegExp(tree) diff --git a/src/routes/organization.ts b/src/routes/organization.ts index 379cfb0..9cbd785 100644 --- a/src/routes/organization.ts +++ b/src/routes/organization.ts @@ -1,11 +1,10 @@ import router from './router' import { Organization, User, Logger, Repository, Module, Interface, Property } from '../models' -import { QueryInclude } from '../models'; +import { QueryInclude } from '../models' import * as _ from 'lodash' import Pagination from './utils/pagination' -import { Op } from 'sequelize'; import OrganizationService from '../service/organization' -import { IFindOptions } from 'sequelize-typescript'; +import { Op, FindOptions } from 'sequelize' router.get('/app/get', async (ctx, next) => { let data: any = {} @@ -15,8 +14,8 @@ router.get('/app/get', async (ctx, next) => { } for (let name in hooks) { if (!query[name]) continue - data[name] = await hooks[name].findById(query[name], { - attributes: { exclude: [] }, + data[name] = await hooks[name].findByPk(query[name], { + attributes: { exclude: [] } }) } ctx.body = { @@ -38,8 +37,12 @@ router.get('/organization/list', async (ctx) => { const total = await OrganizationService.getAllOrganizationIdListNum(curUserId) const pagination = new Pagination(total, ctx.query.cursor || 1, ctx.query.limit || 100) const organizationIds = await OrganizationService.getAllOrganizationIdList(curUserId, pagination, name) - const options: IFindOptions = { - where: { id: { [Op.in]: organizationIds } }, + const options: FindOptions = { + where: { + id: { + [Op.in]: organizationIds, + }, + }, include: [ QueryInclude.Creator, QueryInclude.Owner, @@ -74,7 +77,7 @@ router.get('/organization/owned', async (ctx) => { }) } - let auth = await User.findById(ctx.session.id) + let auth = await User.findByPk(ctx.session.id) let options: any = { where, attributes: { exclude: [] }, @@ -108,7 +111,7 @@ router.get('/organization/joined', async (ctx) => { }) } - let auth = await User.findById(ctx.session.id) + let auth = await User.findByPk(ctx.session.id) let options: object = { where, attributes: { exclude: [] }, @@ -124,7 +127,7 @@ router.get('/organization/joined', async (ctx) => { } }) router.get('/organization/get', async (ctx) => { - let organization = await Organization.findById(ctx.query.id, { + let organization = await Organization.findByPk(ctx.query.id, { attributes: { exclude: [] }, include: [QueryInclude.Creator, QueryInclude.Owner, QueryInclude.Members], } as any) @@ -140,7 +143,7 @@ router.post('/organization/create', async (ctx) => { let members = await User.findAll({ where: { id: body.memberIds } }) await created.$set('members', members) } - let filled = await Organization.findById(created.id, { + let filled = await Organization.findByPk(created.id, { attributes: { exclude: [] }, include: [QueryInclude.Creator, QueryInclude.Owner, QueryInclude.Members], } as any) @@ -155,7 +158,7 @@ router.post('/organization/update', async (ctx, next) => { // delete body.ownerId let updated = await Organization.update(body, { where: { id: body.id } }) if (body.memberIds) { - let reloaded = await Organization.findById(body.id) + let reloaded = await Organization.findByPk(body.id) let members = await User.findAll({ where: { id: body.memberIds } }) ctx.prevAssociations = await reloaded.$get('members') await reloaded.$set('members', members) diff --git a/src/routes/repository.ts b/src/routes/repository.ts index c5d9c3a..4b0600f 100644 --- a/src/routes/repository.ts +++ b/src/routes/repository.ts @@ -3,15 +3,14 @@ import router from './router' import * as _ from 'underscore' import Pagination from './utils/pagination' import { User, Organization, Repository, Module, Interface, Property, QueryInclude, Logger } from '../models' -import { Sequelize } from 'sequelize-typescript' import Tree from './utils/tree' import { AccessUtils, ACCESS_TYPE } from './utils/access' import * as Consts from './utils/const' import RedisService, { CACHE_KEY } from '../service/redis' -import MigrateService from '../service/migrate'; +import MigrateService from '../service/migrate' +import { Op } from 'sequelize' const { initRepository, initModule } = require('./utils/helper') -const Op = Sequelize.Op router.get('/app/get', async (ctx, next) => { let data: any = {} @@ -24,7 +23,7 @@ router.get('/app/get', async (ctx, next) => { } for (let name in hooks) { if (!query[name]) continue - data[name] = await hooks[name].findById(query[name]) + data[name] = await hooks[name].findByPk(query[name]) } ctx.body = { data: Object.assign({}, ctx.body && ctx.body.data, data), @@ -109,13 +108,7 @@ router.get('/repository/owned', async (ctx) => { }) } - let auth: User = await User.findById(ctx.query.user || ctx.session.id) - if (!auth) { - ctx.body = { - isOk: false, - errMsg: '登陆过期了,请重新登陆。', - } - } + let auth: User = await User.findByPk(ctx.query.user || ctx.session.id) // let total = await auth.countOwnedRepositories({ where }) // let pagination = new Pagination(total, ctx.query.cursor || 1, ctx.query.limit || 100) let repositories = await auth.$get('ownedRepositories', { @@ -149,7 +142,7 @@ router.get('/repository/joined', async (ctx) => { }) } - let auth = await User.findById(ctx.query.user || ctx.session.id) + let auth = await User.findByPk(ctx.query.user || ctx.session.id) // let total = await auth.countJoinedRepositories({ where }) // let pagination = new Pagination(total, ctx.query.cursor || 1, ctx.query.limit || 100) let repositories = await auth.$get('joinedRepositories', { @@ -185,11 +178,9 @@ router.get('/repository/get', async (ctx) => { const tryCache = await RedisService.getCache(CACHE_KEY.REPOSITORY_GET, ctx.query.id) let repository: Repository if (tryCache) { - console.log(`from cache`) repository = JSON.parse(tryCache) } else { - console.log(`from db`) - repository = await Repository.findById(ctx.query.id, { + repository = await Repository.findByPk(ctx.query.id, { attributes: { exclude: [] }, include: [ QueryInclude.Creator, @@ -203,7 +194,7 @@ router.get('/repository/get', async (ctx) => { order: [ [{ model: Module, as: 'modules' }, 'priority', 'asc'], [{ model: Module, as: 'modules' }, { model: Interface, as: 'interfaces' }, 'priority', 'asc'] - ] + ] as any }) await RedisService.setCache(CACHE_KEY.REPOSITORY_GET, JSON.stringify(repository), ctx.query.id) } @@ -226,7 +217,7 @@ router.post('/repository/create', async (ctx, next) => { } await initRepository(created) ctx.body = { - data: await Repository.findById(created.id, { + data: await Repository.findByPk(created.id, { attributes: { exclude: [] }, include: [ QueryInclude.Creator, @@ -255,7 +246,7 @@ router.post('/repository/update', async (ctx, next) => { delete body.organizationId let result = await Repository.update(body, { where: { id: body.id } }) if (body.memberIds) { - let reloaded = await Repository.findById(body.id, { + let reloaded = await Repository.findByPk(body.id, { include: [{ model: User, as: 'members', @@ -274,7 +265,7 @@ router.post('/repository/update', async (ctx, next) => { ctx.nextAssociations = reloaded.members } if (body.collaboratorIds) { - let reloaded = await Repository.findById(body.id) + let reloaded = await Repository.findByPk(body.id) let collaborators = await Repository.findAll({ where: { id: { @@ -316,7 +307,7 @@ router.post('/repository/transfer', async (ctx) => { if (ownerId) body.ownerId = ownerId // 转移给其他用户 if (organizationId) { body.organizationId = organizationId // 转移给其他团队,同时转移给该团队拥有者 - body.ownerId = (await Organization.findById(organizationId)).ownerId + body.ownerId = (await Organization.findByPk(organizationId)).ownerId } let result = await Repository.update(body, { where: { id } }) ctx.body = { @@ -389,9 +380,9 @@ router.get('/module/list', async (ctx) => { }) router.get('/module/get', async (ctx) => { ctx.body = { - data: await Module.findById(ctx.query.id, { - attributes: { exclude: [] }, - }), + data: await Module.findByPk(ctx.query.id, { + attributes: { exclude: [] } + }) } }) router.post('/module/create', async (ctx, next) => { @@ -401,7 +392,7 @@ router.post('/module/create', async (ctx, next) => { let created = await Module.create(body) await initModule(created) ctx.body = { - data: await Module.findById(created.id), + data: await Module.findByPk(created.id) } return next() }, async (ctx) => { @@ -447,7 +438,7 @@ router.get('/module/remove', async (ctx, next) => { }, async (ctx) => { if (ctx.body.data === 0) return let { id } = ctx.query - let mod = await Module.findById(id, { paranoid: false }) + let mod = await Module.findByPk(id, { paranoid: false }) await Logger.create({ userId: ctx.session.id, type: 'delete', @@ -464,7 +455,7 @@ router.post('/module/sort', async (ctx) => { }) } if (ids && ids.length) { - const mod = await Module.findById(ids[0]) + const mod = await Module.findByPk(ids[0]) await RedisService.delCache(CACHE_KEY.REPOSITORY_GET, mod.repositoryId) } ctx.body = { @@ -494,15 +485,15 @@ router.get('/interface/list', async (ctx) => { router.get('/interface/get', async (ctx) => { let { id, repositoryId, method, url } = ctx.query - let itf + let itf: any if (id) { - itf = await Interface.findById(id, { - attributes: { exclude: [] }, + itf = await Interface.findByPk(id, { + attributes: { exclude: [] } }) } else if (repositoryId && method && url) { // 同 /app/mock/:repository/:method/:url let urlWithoutPrefixSlash = /(\/)?(.*)/.exec(url)[2] - let repository = await Repository.findById(repositoryId) + let repository = await Repository.findByPk(repositoryId) let collaborators = await repository.$get('collaborators') itf = await Interface.findOne({ @@ -518,11 +509,11 @@ router.get('/interface/get', async (ctx) => { let scopes = ['request', 'response'] for (let i = 0; i < scopes.length; i++) { - let properties = await Property.findAll({ + let properties: any = await Property.findAll({ attributes: { exclude: [] }, where: { interfaceId: itf.id, scope: scopes[i] }, }) - properties = properties.map(item => item.toJSON()) + properties = properties.map((item: any) => item.toJSON()) itf[scopes[i] + 'Properties'] = Tree.ArrayToTree(properties).children } @@ -537,7 +528,7 @@ router.post('/interface/create', async (ctx, next) => { // await initInterface(created) ctx.body = { data: { - itf: await Interface.findById(created.id), + itf: await Interface.findByPk(created.id), } } return next() @@ -559,7 +550,7 @@ router.post('/interface/update', async (ctx, next) => { }) ctx.body = { data: { - itf: await Interface.findById(body.id), + itf: await Interface.findByPk(body.id), } } return next() @@ -579,7 +570,7 @@ router.post('/interface/move', async (ctx) => { const OP_MOVE = 1 const OP_COPY = 2 const { modId, itfId, op } = ctx.request.body - const itf = await Interface.findById(itfId) + const itf = await Interface.findByPk(itfId) if (op === OP_MOVE) { itf.moduleId = modId await Property.update({ @@ -591,7 +582,7 @@ router.post('/interface/move', async (ctx) => { }) await itf.save() } else if (op === OP_COPY) { - const { id, name, ...otherProps } = itf.dataValues + const { id, name, ...otherProps } = itf const newItf = await Interface.create({ name: name + '副本', ...otherProps, @@ -604,7 +595,7 @@ router.post('/interface/move', async (ctx) => { } }) for (const property of properties) { - const { id, ...props } = property.dataValues + const { id, ...props } = property await Property.create({ ...props, interfaceId: newItf.id, @@ -630,7 +621,7 @@ router.get('/interface/remove', async (ctx, next) => { }, async (ctx) => { if (ctx.body.data === 0) return let { id } = ctx.query - let itf = await Interface.findById(id, { paranoid: false }) + let itf = await Interface.findByPk(id, { paranoid: false }) await Logger.create({ userId: ctx.session.id, type: 'delete', @@ -641,7 +632,7 @@ router.get('/interface/remove', async (ctx, next) => { }) router.get('/__test__', async (ctx) => { - const itf = await Interface.findById(5331) + const itf = await Interface.findByPk(5331) itf.name = itf.name + '+' await itf.save() ctx.body = { @@ -656,7 +647,7 @@ router.post('/interface/lock', async (ctx, next) => { } let { id } = ctx.request.body - let itf = await Interface.findById(id, { + let itf = await Interface.findByPk(id, { attributes: ['lockerId'], include: [ QueryInclude.Locker, @@ -670,7 +661,7 @@ router.post('/interface/lock', async (ctx, next) => { } await Interface.update({ lockerId: ctx.session.id }, { where: { id } }) - itf = await Interface.findById(id, { + itf = await Interface.findByPk(id, { attributes: ['lockerId'], include: [ QueryInclude.Locker, @@ -689,7 +680,7 @@ router.post('/interface/unlock', async (ctx) => { } let { id } = ctx.request.body - let itf = await Interface.findById(id, { attributes: ['lockerId'] }) + let itf = await Interface.findByPk(id, { attributes: ['lockerId'] }) if (itf.lockerId !== ctx.session.id) { // DONE 2.3 BUG 接口可能被其他人解锁。如果不是同一个用户,则忽略。 ctx.body = { isOk: false, @@ -745,9 +736,9 @@ router.get('/property/list', async (ctx) => { router.get('/property/get', async (ctx) => { let { id } = ctx.query ctx.body = { - data: await Property.findById(id, { - attributes: { exclude: [] }, - }), + data: await Property.findByPk(id, { + attributes: { exclude: [] } + }) } }) @@ -756,9 +747,9 @@ router.post('/property/create', async (ctx) => { let body = Object.assign(ctx.request.body, { creatorId }) let created = await Property.create(body) ctx.body = { - data: await Property.findById(created.id, { - attributes: { exclude: [] }, - }), + data: await Property.findByPk(created.id, { + attributes: { exclude: [] } + }) } }) @@ -767,7 +758,7 @@ router.post('/property/update', async (ctx) => { properties = Array.isArray(properties) ? properties : [properties] let result = 0 for (let item of properties) { - let property = _.pick(item, Object.keys(Property.attributes)) + let property = _.pick(item, Object.keys(Property.rawAttributes)) let affected = await Property.update(property, { where: { id: property.id }, }) @@ -783,7 +774,7 @@ router.post('/properties/update', async (ctx, next) => { let { properties, summary } = ctx.request.body // JSON.parse(ctx.request.body) properties = Array.isArray(properties) ? properties : [properties] - let itf = await Interface.findById(itfId) + let itf = await Interface.findByPk(itfId) if (summary.name) { itf.name = summary.name @@ -848,7 +839,7 @@ router.post('/properties/update', async (ctx, next) => { where: { id: item.id }, }) } - itf = await Interface.findById(itfId, { + itf = await Interface.findByPk(itfId, { include: (QueryInclude.RepositoryHierarchy as any).include[0].include, }) ctx.body = { @@ -860,8 +851,8 @@ router.post('/properties/update', async (ctx, next) => { return next() }, async (ctx) => { if (ctx.body.data === 0) return - let itf = await Interface.findById(ctx.query.itf, { - attributes: { exclude: [] }, + let itf = await Interface.findByPk(ctx.query.itf, { + attributes: { exclude: [] } }) await Logger.create({ userId: ctx.session.id, diff --git a/src/routes/utils/tree.ts b/src/routes/utils/tree.ts index 08746e7..aec71cc 100644 --- a/src/routes/utils/tree.ts +++ b/src/routes/utils/tree.ts @@ -1,4 +1,4 @@ -import { Property } from "../../models"; +import { Property } from "../../models" import * as _ from 'underscore' const vm = require('vm') import * as Mock from 'mockjs' diff --git a/src/scripts/app.ts b/src/scripts/app.ts index b7daded..7f5614d 100644 --- a/src/scripts/app.ts +++ b/src/scripts/app.ts @@ -20,7 +20,7 @@ app.use(session({ if (process.env.NODE_ENV === 'development' && process.env.TEST_MODE !== 'true') app.use(logger()) app.use(async (ctx, next) => { - ctx.set('Access-Control-Allow-Origin', '*'); + ctx.set('Access-Control-Allow-Origin', '*') ctx.set('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS') ctx.set('Access-Control-Allow-Credentials', 'true') await next() diff --git a/src/scripts/init/delos.ts b/src/scripts/init/delos.ts index cfd767d..a555ad0 100644 --- a/src/scripts/init/delos.ts +++ b/src/scripts/init/delos.ts @@ -134,12 +134,12 @@ export async function after () { // console.log(JSON.stringify(repositories, null, 2)) console.log(repositories.map(item => item.toJSON())) - let admin = await User.findById(BO_ADMIN.id) + let admin = await User.findByPk(BO_ADMIN.id) // for (let k in admin) console.log(k) let owned: any = await admin.$get('ownedOrganizations') console.log(owned.map((item: any) => item.toJSON())) - let mozhi = await User.findById(BO_MOZHI.id) + let mozhi = await User.findByPk(BO_MOZHI.id) for (let k in mozhi) console.log(k) let joined: any = await mozhi.$get('joinedOrganizations') console.log(joined.map((item: any) => item.toJSON())) diff --git a/src/service/migrate.ts b/src/service/migrate.ts index 4937392..826abfd 100644 --- a/src/service/migrate.ts +++ b/src/service/migrate.ts @@ -1,5 +1,5 @@ -import { Repository, Module, Interface, Property, User } from "../models"; -import { SCOPES } from "../models/bo/property"; +import { Repository, Module, Interface, Property, User } from "../models" +import { SCOPES } from "../models/bo/property" import * as md5 from 'md5' import * as querystring from 'querystring' import * as rp from 'request-promise' diff --git a/src/service/organization.ts b/src/service/organization.ts index 7e12d67..33c3803 100644 --- a/src/service/organization.ts +++ b/src/service/organization.ts @@ -1,7 +1,6 @@ import seq from '../models/sequelize' import Pagination from '../routes/utils/pagination' -import Utils from './utils'; - +import Utils from './utils' export default class OrganizationService { public static canUserAccessOrganization(userId: number, organizationId: number): Promise { const sql = ` diff --git a/src/service/postman.ts b/src/service/postman.ts index 797e8fe..c3a3d44 100644 --- a/src/service/postman.ts +++ b/src/service/postman.ts @@ -1,14 +1,14 @@ import { PostmanCollection, Folder, Item } from "../types/postman" import { Repository, Interface, Module, Property } from "../models" import * as url from 'url' -import { REQUEST_PARAMS_TYPE } from "../models/bo/property"; +import { REQUEST_PARAMS_TYPE } from "../models/bo/property" import UrlUtils from "../routes/utils/url" const SCHEMA_V_2_1_0 = 'https://schema.getpostman.com/json/collection/v2.1.0/collection.json' export default class PostmanService { public static async export(repositoryId: number): Promise { - const repo = await Repository.findById(repositoryId, { + const repo = await Repository.findByPk(repositoryId, { include: [{ model: Module, as: 'modules', diff --git a/src/service/repository.ts b/src/service/repository.ts index 731a8f2..dfe70c1 100644 --- a/src/service/repository.ts +++ b/src/service/repository.ts @@ -1,9 +1,9 @@ import { Repository, RepositoriesMembers } from "../models" -import OrganizationService from "./organization"; +import OrganizationService from "./organization" export default class RepositoryService { public static async canUserAccessRepository(userId: number, repositoryId: number): Promise { - const repo = await Repository.findById(repositoryId) + const repo = await Repository.findByPk(repositoryId) if (!repo) return false if (repo.creatorId === userId || repo.ownerId === userId) return true const memberExistsNum = await RepositoriesMembers.count({ diff --git a/src/types/index.d.ts b/src/types/index.d.ts index 0a78408..3785673 100644 --- a/src/types/index.d.ts +++ b/src/types/index.d.ts @@ -2,6 +2,7 @@ import { PoolOptions } from "sequelize"; import { ISequelizeConfig } from "sequelize-typescript"; import { RedisOptions } from "koa-redis"; +import { PoolOptions } from "sequelize" declare interface RedisAndClusterOptions extends RedisOptions { isRedisCluster?: boolean; diff --git a/src/types/postman.d.ts b/src/types/postman.d.ts index b69df36..5fbe7ec 100644 --- a/src/types/postman.d.ts +++ b/src/types/postman.d.ts @@ -7,11 +7,11 @@ /** * A collection's friendly name is defined by this field. You would want to set this field to a value that would allow you to easily identify this collection among a bunch of other collections, as such outlining its usage or content. */ -export type NameOfTheCollection = string; +export type NameOfTheCollection = string /** * A Description can be a raw text, or be an object, which holds the description along with its format. */ -export type DefinitionsDescription = Description | string | null; +export type DefinitionsDescription = Description | string | null /** * Postman allows you to version your collections as they grow, and this field holds the version number. While optional, it is recommended that you use this field to its fullest extent! */ @@ -20,42 +20,42 @@ export type CollectionVersion = /** * Increment this number if you make changes to the collection that changes its behaviour. E.g: Removing or adding new test scripts. (partly or completely). */ - major: number; + major: number /** * You should increment this number if you make changes that will not break anything that uses the collection. E.g: removing a folder. */ - minor: number; + minor: number /** * Ideally, minor changes to a collection should result in the increment of this number. */ - patch: number; + patch: number /** * A human friendly identifier to make sense of the version numbers. E.g: 'beta-3' */ - identifier?: string; - meta?: any; - [k: string]: any; + identifier?: string + meta?: any + [k: string]: any } - | string; -export type Items1 = Item | Folder; + | string +export type Items1 = Item | Folder /** * Using variables in your Postman requests eliminates the need to duplicate requests, which can save a lot of time. Variables can be defined, and referenced to from any part of a request. */ export type Variable = | { - [k: string]: any; + [k: string]: any } | { - [k: string]: any; + [k: string]: any } | { - [k: string]: any; - }; + [k: string]: any + } /** * Collection variables allow you to define a set of variables, that are a *part of the collection*, as opposed to environments, which are separate entities. * *Note: Collection variables must not contain any sensitive information.* */ -export type VariableList = Variable[]; +export type VariableList = Variable[] /** * If object, contains the complete broken-down URL for this request. If string, contains the literal request URL. */ @@ -64,170 +64,170 @@ export type Url = /** * The string representation of the request URL, including the protocol, host, path, hash, query parameter(s) and path variable(s). */ - raw?: string; + raw?: string /** * The protocol associated with the request, E.g: 'http' */ - protocol?: string; - host?: Host; + protocol?: string + host?: Host path?: | string | ( | string | { - type?: string; - value?: string; - [k: string]: any; - })[]; + type?: string + value?: string + [k: string]: any + })[] /** * The port number present in this URL. An empty value implies 80/443 depending on whether the protocol field contains http/https. */ - port?: string; + port?: string /** * An array of QueryParams, which is basically the query string part of the URL, parsed into separate variables */ - query?: QueryParam[]; + query?: QueryParam[] /** * Contains the URL fragment (if any). Usually this is not transmitted over the network, but it could be useful to store this in some cases. */ - hash?: string; + hash?: string /** * Postman supports path variables with the syntax `/path/:variableName/to/somewhere`. These variables are stored in this field. */ - variable?: Variable[]; - [k: string]: any; + variable?: Variable[] + [k: string]: any } - | string; + | string /** * The host for the URL, E.g: api.yourdomain.com. Can be stored as a string or as an array of strings. */ -export type Host = string | string[]; +export type Host = string | string[] /** * Postman allows you to configure scripts to run when specific events occur. These scripts are stored here, and can be referenced in the collection by their ID. */ -export type EventList = Event[]; +export type EventList = Event[] /** * A request represents an HTTP request. If a string, the string is assumed to be the request URL and the method is assumed to be 'GET'. */ -export type Request1 = Request | string; +export type Request1 = Request | string /** * The attributes for [AWS Auth](http://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html). */ -export type AwsSignatureV4 = Auth1[]; +export type AwsSignatureV4 = Auth1[] /** * The attributes for [Basic Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication). */ -export type BasicAuthentication = Auth1[]; +export type BasicAuthentication = Auth1[] /** * The helper attributes for [Bearer Token Authentication](https://tools.ietf.org/html/rfc6750) */ -export type BearerTokenAuthentication = Auth1[]; +export type BearerTokenAuthentication = Auth1[] /** * The attributes for [Digest Authentication](https://en.wikipedia.org/wiki/Digest_access_authentication). */ -export type DigestAuthentication = Auth1[]; +export type DigestAuthentication = Auth1[] /** * The attributes for [Hawk Authentication](https://github.com/hueniverse/hawk) */ -export type HawkAuthentication = Auth1[]; +export type HawkAuthentication = Auth1[] /** * The attributes for [NTLM Authentication](https://msdn.microsoft.com/en-us/library/cc237488.aspx) */ -export type NtlmAuthentication = Auth1[]; +export type NtlmAuthentication = Auth1[] /** * The attributes for [OAuth2](https://oauth.net/1/) */ -export type OAuth1 = Auth1[]; +export type OAuth1 = Auth1[] /** * Helper attributes for [OAuth2](https://oauth.net/2/) */ -export type OAuth2 = Auth1[]; +export type OAuth2 = Auth1[] /** * A representation for a list of headers */ -export type HeaderList = Header[]; +export type HeaderList = Header[] export type FormParameter = | { - key: string; - value?: string; + key: string + value?: string /** * When set to true, prevents this form data entity from being sent. */ - disabled?: boolean; - type?: "text"; - description?: DefinitionsDescription; - [k: string]: any; + disabled?: boolean + type?: "text" + description?: DefinitionsDescription + [k: string]: any } | { - key: string; - src?: string; + key: string + src?: string /** * When set to true, prevents this form data entity from being sent. */ - disabled?: boolean; - type?: "file"; - description?: DefinitionsDescription; - [k: string]: any; - }; + disabled?: boolean + type?: "file" + description?: DefinitionsDescription + [k: string]: any + } /** * The time taken by the request to complete. If a number, the unit is milliseconds. If the response is manually created, this can be set to `null`. */ -export type ResponseTime = null | string | number; -export type Headers = Header2 | string; -export type Header1 = string; +export type ResponseTime = null | string | number +export type Headers = Header2 | string +export type Header1 = string /** * No HTTP request is complete without its headers, and the same is true for a Postman request. This field is an array containing all the headers. */ -export type Header2 = (Header | Header1)[]; -export type Responses = Response[]; -export type Items = Item | Folder; +export type Header2 = (Header | Header1)[] +export type Responses = Response[] +export type Items = Item | Folder export interface PostmanCollection { - info: Information; + info: Information /** * Items are the basic unit for a Postman collection. You can think of them as corresponding to a single API endpoint. Each Item has one request and may have multiple API responses associated with it. */ - item: Items1[]; - event?: EventList; - variable?: VariableList; - auth?: null | Auth; - [k: string]: any; + item: Items1[] + event?: EventList + variable?: VariableList + auth?: null | Auth + [k: string]: any } /** * Detailed description of the info block */ export interface Information { - name: NameOfTheCollection; + name: NameOfTheCollection /** * Every collection is identified by the unique value of this field. The value of this field is usually easiest to generate using a UID generator function. If you already have a collection, it is recommended that you maintain the same id since changing the id usually implies that is a different collection than it was originally. * *Note: This field exists for compatibility reasons with Collection Format V1.* */ - _postman_id?: string; - description?: DefinitionsDescription; - version?: CollectionVersion; + _postman_id?: string + description?: DefinitionsDescription + version?: CollectionVersion /** * This should ideally hold a link to the Postman schema that is used to validate this collection. E.g: https://schema.getpostman.com/collection/v1 */ - schema: string; - [k: string]: any; + schema: string + [k: string]: any } export interface Description { /** * The content of the description goes here, as a raw string. */ - content?: string; + content?: string /** * Holds the mime type of the raw description content. E.g: 'text/markdown' or 'text/html'. * The type is used to correctly render the description when generating documentation, or in the Postman app. */ - type?: string; + type?: string /** * Description can have versions associated with it, which should be put in this property. */ version?: { - [k: string]: any; - }; - [k: string]: any; + [k: string]: any + } + [k: string]: any } /** * Items are entities which contain an actual HTTP request, and sample responses attached to it. @@ -236,17 +236,17 @@ export interface Item { /** * A unique ID that is used to identify collections internally */ - id?: string; + id?: string /** * A human readable identifier for the current item. */ - name?: string; - description?: DefinitionsDescription; - variable?: VariableList; - event?: EventList; - request: Request1; - response?: Responses; - [k: string]: any; + name?: string + description?: DefinitionsDescription + variable?: VariableList + event?: EventList + request: Request1 + response?: Responses + [k: string]: any } /** * Defines a script associated with an associated event name @@ -255,17 +255,17 @@ export interface Event { /** * A unique identifier for the enclosing event. */ - id?: string; + id?: string /** * Can be set to `test` or `prerequest` for test scripts or pre-request scripts respectively. */ - listen: string; - script?: Script; + listen: string + script?: Script /** * Indicates whether the event is disabled. If absent, the event is assumed to be enabled. */ - disabled?: boolean; - [k: string]: any; + disabled?: boolean + [k: string]: any } /** * A script is a snippet of Javascript code that can be used to to perform setup or teardown operations on a particular response. @@ -274,34 +274,34 @@ export interface Script { /** * A unique, user defined identifier that can be used to refer to this script from requests. */ - id?: string; + id?: string /** * Type of the script. E.g: 'text/javascript' */ - type?: string; - exec?: string[] | string; - src?: Url; + type?: string + exec?: string[] | string + src?: Url /** * Script name */ - name?: string; - [k: string]: any; + name?: string + [k: string]: any } export interface QueryParam { - key?: string | null; - value?: string | null; + key?: string | null + value?: string | null /** * If set to true, the current query parameter will not be sent with the request. */ - disabled?: boolean; - description?: DefinitionsDescription; - [k: string]: any; + disabled?: boolean + description?: DefinitionsDescription + [k: string]: any } export interface Request { - url?: Url; - auth?: null | Auth; - proxy?: ProxyConfig; - certificate?: Certificate; + url?: Url + auth?: null | Auth + proxy?: ProxyConfig + certificate?: Certificate /** * The HTTP method associated with this request. */ @@ -320,9 +320,9 @@ export interface Request { | "LOCK" | "UNLOCK" | "PROPFIND" - | "VIEW"; - description?: DefinitionsDescription; - header?: HeaderList | string; + | "VIEW" + description?: DefinitionsDescription + header?: HeaderList | string /** * This field contains the data usually contained in the request body. */ @@ -330,46 +330,46 @@ export interface Request { /** * Postman stores the type of data associated with this request in this field. */ - mode?: "raw" | "urlencoded" | "formdata" | "file"; - raw?: string; - urlencoded?: UrlEncodedParameter[]; - formdata?: FormParameter[]; + mode?: "raw" | "urlencoded" | "formdata" | "file" + raw?: string + urlencoded?: UrlEncodedParameter[] + formdata?: FormParameter[] file?: { /** * Contains the name of the file to upload. _Not the path_. */ - src?: string; - content?: string; - [k: string]: any; - }; - [k: string]: any; - }; - [k: string]: any; + src?: string + content?: string + [k: string]: any + } + [k: string]: any + } + [k: string]: any } /** * Represents authentication helpers provided by Postman */ export interface Auth { - type: "awsv4" | "basic" | "bearer" | "digest" | "hawk" | "noauth" | "oauth1" | "oauth2" | "ntlm"; - noauth?: any; - awsv4?: AwsSignatureV4; - basic?: BasicAuthentication; - bearer?: BearerTokenAuthentication; - digest?: DigestAuthentication; - hawk?: HawkAuthentication; - ntlm?: NtlmAuthentication; - oauth1?: OAuth1; - oauth2?: OAuth2; - [k: string]: any; + type: "awsv4" | "basic" | "bearer" | "digest" | "hawk" | "noauth" | "oauth1" | "oauth2" | "ntlm" + noauth?: any + awsv4?: AwsSignatureV4 + basic?: BasicAuthentication + bearer?: BearerTokenAuthentication + digest?: DigestAuthentication + hawk?: HawkAuthentication + ntlm?: NtlmAuthentication + oauth1?: OAuth1 + oauth2?: OAuth2 + [k: string]: any } /** * Represents an attribute for any authorization method provided by Postman. For example `username` and `password` are set as auth attributes for Basic Authentication method. */ export interface Auth1 { - key: string; - value?: any; - type?: string; - [k: string]: any; + key: string + value?: any + type?: string + [k: string]: any } /** * Using the Proxy, you can configure your custom proxy into the postman for particular url match @@ -378,24 +378,24 @@ export interface ProxyConfig { /** * The Url match for which the proxy config is defined */ - match?: string; + match?: string /** * The proxy server host */ - host?: string; + host?: string /** * The proxy server port */ - port?: number; + port?: number /** * The tunneling details for the proxy config */ - tunnel?: boolean; + tunnel?: boolean /** * When set to true, ignores this proxy configuration entity */ - disabled?: boolean; - [k: string]: any; + disabled?: boolean + [k: string]: any } /** * A representation of an ssl certificate @@ -404,11 +404,11 @@ export interface Certificate { /** * A name for the certificate for user reference */ - name?: string; + name?: string /** * A list of Url match pattern strings, to identify Urls this certificate can be used for. */ - matches?: any[]; + matches?: any[] /** * An object containing path to file containing private key, on the file system */ @@ -417,10 +417,10 @@ export interface Certificate { * The path to file containing key for certificate, on the file system */ src?: { - [k: string]: any; - }; - [k: string]: any; - }; + [k: string]: any + } + [k: string]: any + } /** * An object containing path to file certificate, on the file system */ @@ -429,15 +429,15 @@ export interface Certificate { * The path to file containing key for certificate, on the file system */ src?: { - [k: string]: any; - }; - [k: string]: any; - }; + [k: string]: any + } + [k: string]: any + } /** * The passphrase for the certificate */ - passphrase?: string; - [k: string]: any; + passphrase?: string + [k: string]: any } /** * Represents a single HTTP Header @@ -446,24 +446,24 @@ export interface Header { /** * This holds the LHS of the HTTP Header, e.g ``Content-Type`` or ``X-Custom-Header`` */ - key: string; + key: string /** * The value (or the RHS) of the Header is stored in this field. */ - value: string; + value: string /** * If set to true, the current header will not be sent with requests. */ - disabled?: boolean; - description?: DefinitionsDescription; - [k: string]: any; + disabled?: boolean + description?: DefinitionsDescription + [k: string]: any } export interface UrlEncodedParameter { - key: string; - value?: string; - disabled?: boolean; - description?: DefinitionsDescription; - [k: string]: any; + key: string + value?: string + disabled?: boolean + description?: DefinitionsDescription + [k: string]: any } /** * A response represents an HTTP response. @@ -472,24 +472,24 @@ export interface Response { /** * A unique, user defined identifier that can be used to refer to this response from requests. */ - id?: string; - originalRequest?: Request1; - responseTime?: ResponseTime; - header?: Headers; - cookie?: Cookie[]; + id?: string + originalRequest?: Request1 + responseTime?: ResponseTime + header?: Headers + cookie?: Cookie[] /** * The raw text of the response. */ - body?: string; + body?: string /** * The response status, e.g: '200 OK' */ - status?: string; + status?: string /** * The numerical response code, example: 200, 201, 404, etc. */ - code?: number; - [k: string]: any; + code?: number + [k: string]: any } /** * A Cookie, that follows the [Google Chrome format](https://developer.chrome.com/extensions/cookies) @@ -498,45 +498,45 @@ export interface Cookie { /** * The domain for which this cookie is valid. */ - domain: string; + domain: string /** * When the cookie expires. */ - expires?: string | number; - maxAge?: string; + expires?: string | number + maxAge?: string /** * True if the cookie is a host-only cookie. (i.e. a request's URL domain must exactly match the domain of the cookie). */ - hostOnly?: boolean; + hostOnly?: boolean /** * Indicates if this cookie is HTTP Only. (if True, the cookie is inaccessible to client-side scripts) */ - httpOnly?: boolean; + httpOnly?: boolean /** * This is the name of the Cookie. */ - name?: string; + name?: string /** * The path associated with the Cookie. */ - path: string; + path: string /** * Indicates if the 'secure' flag is set on the Cookie, meaning that it is transmitted over secure connections only. (typically HTTPS) */ - secure?: boolean; + secure?: boolean /** * True if the cookie is a session cookie. */ - session?: boolean; + session?: boolean /** * The value of the Cookie. */ - value?: string; + value?: string /** * Custom attributes for a cookie go here, such as the [Priority Field](https://code.google.com/p/chromium/issues/detail?id=232693) */ - extensions?: any[]; - [k: string]: any; + extensions?: any[] + [k: string]: any } /** * One of the primary goals of Postman is to organize the development of APIs. To this end, it is necessary to be able to group requests together. This can be achived using 'Folders'. A folder just is an ordered set of requests. @@ -545,14 +545,14 @@ export interface Folder { /** * A folder's friendly name is defined by this field. You would want to set this field to a value that would allow you to easily identify this folder. */ - name?: string; - description?: DefinitionsDescription; - variable?: VariableList; + name?: string + description?: DefinitionsDescription + variable?: VariableList /** * Items are entities which contain an actual HTTP request, and sample responses attached to it. Folders may contain many items. */ - item: Items[]; - event?: EventList; - auth?: null | Auth; - [k: string]: any; + item: Items[] + event?: EventList + auth?: null | Auth + [k: string]: any } diff --git a/test/mocha.opts b/test/mocha.opts index 2f58f39..58d75fe 100644 --- a/test/mocha.opts +++ b/test/mocha.opts @@ -1,6 +1,6 @@ --allow-uncaught --exit ---timeout 5000 +--timeout 15000 --slow 200 test/**/*.js \ No newline at end of file diff --git a/test/test.interface.js b/test/test.interface.js index d8136c8..81ba47e 100755 --- a/test/test.interface.js +++ b/test/test.interface.js @@ -27,7 +27,7 @@ describe('Interface', () => { }) let validInterface = (itf, extras = []) => { itf.should.be.a('object').have.all.keys( - Object.keys(Interface.attributes).concat(extras) + Object.keys(Interface.rawAttributes).concat(extras) ) itf.creatorId.should.be.a('number') itf.repositoryId.should.be.a('number') diff --git a/test/test.module.js b/test/test.module.js index 044e6c8..e52064c 100755 --- a/test/test.module.js +++ b/test/test.module.js @@ -22,7 +22,7 @@ describe('Module', () => { }) let validModule = (mod) => { mod.should.be.a('object').have.all.keys( - Object.keys(Module.attributes) + Object.keys(Module.rawAttributes) ) mod.creatorId.should.be.a('number') mod.repositoryId.should.be.a('number') diff --git a/test/test.organization.js b/test/test.organization.js index 76cc95e..7e8ce33 100755 --- a/test/test.organization.js +++ b/test/test.organization.js @@ -23,7 +23,7 @@ describe('Organization', () => { }) let validOrganization = (organization) => { organization.should.be.a('object').have.all.keys( - [...Object.keys(Organization.attributes), 'creator', 'owner', 'members'] + [...Object.keys(Organization.rawAttributes), 'creator', 'owner', 'members'] ) let { creator, owner, members } = organization creator.should.be.a('object').have.all.keys(['id', 'fullname', 'email']) diff --git a/test/test.property.js b/test/test.property.js index c3e7fcf..572da72 100755 --- a/test/test.property.js +++ b/test/test.property.js @@ -33,7 +33,7 @@ describe('Property', () => { }) let validProperty = (property) => { property.should.be.a('object').have.all.keys( - Object.keys(Property.attributes) + Object.keys(Property.rawAttributes) ) property.creatorId.should.be.a('number') property.repositoryId.should.be.a('number') diff --git a/test/test.repository.js b/test/test.repository.js index 5219d30..57dd37f 100755 --- a/test/test.repository.js +++ b/test/test.repository.js @@ -23,7 +23,7 @@ describe('Repository', () => { }) let validRepository = (repository, deep) => { repository.should.be.a('object').have.all.keys( - [...Object.keys(Repository.attributes), 'creator', 'owner', 'members', 'locker', 'organization', 'collaborators'] + [...Object.keys(Repository.rawAttributes), 'creator', 'owner', 'members', 'locker', 'organization', 'collaborators'] .concat(deep ? ['modules'] : []) ) let { creator, owner, members } = repository diff --git a/tsconfig.json b/tsconfig.json index 1bacc9b..ff76b18 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,11 +1,11 @@ { "compilerOptions": { - "outDir": "dist", + "outDir": "./dist", "module": "commonjs", "moduleResolution": "node", "experimentalDecorators": true, "emitDecoratorMetadata": true, - "target": "es6", + "target": "esnext", "removeComments": true, "sourceMap": true, "watch": false, diff --git a/tslint.json b/tslint.json index 9fc8cf0..8af2de9 100644 --- a/tslint.json +++ b/tslint.json @@ -1,69 +1,69 @@ { - "tslint.enable": true, - "rules": { - "class-name": true, - "comment-format": [ - true, - "check-space" - ], - "indent": [ - true, - "spaces", - 2 - ], - "one-line": [ - true, - "check-open-brace", - "check-whitespace" - ], - "no-var-keyword": true, - "quotemark": [ - false, - "double", - "avoid-escape" - ], - "semicolon": [ - false, - "always", - "ignore-bound-class-methods" - ], - "whitespace": [ - true, - "check-branch", - "check-decl", - "check-operator", - "check-module", - "check-separator", - "check-type" - ], - "trailing-comma": [ - false, - { - "multiline": "always", - "singleline": "never" - } - ], - "typedef-whitespace": [ - true, - { - "call-signature": "nospace", - "index-signature": "nospace", - "parameter": "nospace", - "property-declaration": "nospace", - "variable-declaration": "nospace" - }, - { - "call-signature": "onespace", - "index-signature": "onespace", - "parameter": "onespace", - "property-declaration": "onespace", - "variable-declaration": "onespace" - } - ], - "no-internal-module": true, - "no-trailing-whitespace": true, - "no-null-keyword": true, - "prefer-const": false, - "jsdoc-format": true - } + "tslint.enable": true, + "rules": { + "class-name": true, + "comment-format": [ + true, + "check-space" + ], + "indent": [ + true, + "spaces", + 2 + ], + "one-line": [ + true, + "check-open-brace", + "check-whitespace" + ], + "no-var-keyword": true, + "quotemark": [ + false, + "double", + "avoid-escape" + ], + "semicolon": [ + true, + "never", + "ignore-bound-class-methods" + ], + "whitespace": [ + true, + "check-branch", + "check-decl", + "check-operator", + "check-module", + "check-separator", + "check-type" + ], + "trailing-comma": [ + false, + { + "multiline": "always", + "singleline": "never" + } + ], + "typedef-whitespace": [ + true, + { + "call-signature": "nospace", + "index-signature": "nospace", + "parameter": "nospace", + "property-declaration": "nospace", + "variable-declaration": "nospace" + }, + { + "call-signature": "onespace", + "index-signature": "onespace", + "parameter": "onespace", + "property-declaration": "onespace", + "variable-declaration": "onespace" + } + ], + "no-internal-module": true, + "no-trailing-whitespace": true, + "no-null-keyword": true, + "prefer-const": false, + "jsdoc-format": true + } } \ No newline at end of file