Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/models/System.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { model, SchemaDefinition, Model as M } from "mongoose";
import { Base, IDoc, IDocRaw, MODIFY_MOTHODS } from "./common";
import newCache = require("@utils/newCache");

export const FLAG = "system";
export const FLAG = "systems";

export const cache = newCache(FLAG);

Expand Down
8 changes: 1 addition & 7 deletions src/modules/database/database.providers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,7 @@ export const connectDatabase = () => {
};

export const injectData = async () => {
let num = await UsersModel.count({ }).exec();
if (num === 0) {
return UsersModel.addUser(
config.defaults.user.name, config.defaults.user.pass
);
}
num = await UsergroupsModel.count({ }).exec();
const num = await UsergroupsModel.count({ }).exec();
if (num === 0) {
const group = await UsergroupsModel.create({
name: config.defaults.group.name
Expand Down
5 changes: 3 additions & 2 deletions src/modules/goods/goods.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ export class GoodsAdminController {
active: true
})).toObject();
} catch (error) {
fs.remove(obj.file.path);
if (cb) {
cb("Good", error);
} else {
Expand Down Expand Up @@ -168,7 +169,7 @@ export class GoodsAdminController {
appends: await this.getCategoriesIds(query.append || [])
};

return await this.fileProcess(
return this.fileProcess(
{ file, uploader: uploaderId, opt: fileProcessOpts },
(type, error) => {
if (type === "Categories") {
Expand All @@ -179,7 +180,7 @@ export class GoodsAdminController {
}
}
if (type === "Good") {
throw new BadRequestException(error.toString());
throw error;
}
}
);
Expand Down
2 changes: 1 addition & 1 deletion src/services/base.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ abstract class ModelService<D extends IDocRaw> {
return Promise.resolve({ });
}

private runBeforeEach() {
protected runBeforeEach() {
return Promise.resolve(this.beforeEach());
}

Expand Down
24 changes: 24 additions & 0 deletions src/services/users.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Model as UserUsergroupsModel } from "@models/User-Usergroup";
import { IUsergroups } from "@models/Usergroup";
import { SystemService } from "@services/system";
import { BaseService, IGetOptions } from "@services/base";
import { config } from "@utils/config";

@Component()
export class UsersService extends BaseService<IUser> {
Expand All @@ -15,7 +16,26 @@ export class UsersService extends BaseService<IUser> {
this.setModel(UsersModel);
}

protected async beforeEach() {
const num = await cache.get("total") ||
await UsersModel.count({ }).exec();
if (num !== 0) {
return;
}
const user = await UsersModel.addUser(
config.defaults.user.name, config.defaults.user.pass
);
const gid = await this.sysSvr.getDefaultUsergroup();
if (gid) {
await UserUsergroupsModel.create({
user: user._id, usergroup: gid
});
}
}

public async addUser(obj, gid?: ObjectId) {
await this.runBeforeAll();
await this.runBeforeEach();
try {
const user = await UsersModel.addUser(obj.username, obj.password);
if (!gid) {
Expand All @@ -40,6 +60,8 @@ export class UsersService extends BaseService<IUser> {
}

public async isVaild(username: string, password: string) {
await this.runBeforeAll();
await this.runBeforeEach();
try {
return await UsersModel.isVaild(username, password);
} catch (err) {
Expand All @@ -54,6 +76,8 @@ export class UsersService extends BaseService<IUser> {
public async getUsergroups(
uid: ObjectId, pageObj = this.DEF_PER_OBJ
) {
await this.runBeforeAll();
await this.runBeforeEach();
const perNum = pageObj.perNum || this.DEF_PER_OBJ.perNum;
const page = pageObj.page || this.DEF_PER_OBJ.page;
const groups = await UserUsergroupsModel
Expand Down
68 changes: 15 additions & 53 deletions test/api/collections/collections_token.e2e.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,16 @@
import supertest = require("supertest");
import faker = require("faker");
import { basename } from "path";
import fs = require("fs-extra");
import { Model as TokensModel } from "@models/Token";
import { config } from "@utils/config";
import { Model as GoodsModels } from "@models/Good";

import {
connect, drop, newUser, addCategoryAndRegexp
connect, drop, addCategoryAndRegexp
} from "../../helpers/database";
import { init } from "../../helpers/server";
import { uploadFiles, newFile } from "../../helpers/files";
import { newIds } from "../../helpers/utils";
import { TokenRequest, GuestRequest } from "../../helpers/request";
import * as files from "../../helpers/files";

describe("Token to Upload Files Api", () => {

let request: supertest.SuperTest<supertest.Test>;
let request: TokenRequest;

before(() => {
return connect();
Expand All @@ -27,30 +22,23 @@ describe("Token to Upload Files Api", () => {
return drop(ids);
});

before(async () => {
request = await init();
const filepaths = [ ];

after(() => {
return files.remove(filepaths);
});

before("login", async () => {
const req = new GuestRequest(await init(), ids, filepaths);
request = await req.loginWithToken();
});

const FILE_COUNST = 10;
const filepaths = [ ];
const prefix = `${faker.random.word()}_`;
before(async () => {
// Generator Files
for (let i = 0; i < FILE_COUNST; i++) {
filepaths.push(await newFile(`${prefix}${faker.random.uuid()}`));
}
});

after(async () => {
for (const filepath of filepaths) {
fs.removeSync(filepath);
const good = (await GoodsModels.findOne({
originname: basename(filepath)
}).exec()).toObject();
fs.removeSync(
`${config.paths.upload}/${good.category}/${good.filename}`
);
await GoodsModels.findByIdAndRemove(good._id).exec();
await request.newFile(`${prefix}${faker.random.uuid()}`);
}
});

Expand All @@ -62,37 +50,11 @@ describe("Token to Upload Files Api", () => {
ids.regexps.push(docs[1]._id);
});

const user = {
name: faker.name.firstName(),
pass: faker.random.words(),
token: ""
};
step("Login", async () => {
const doc = await newUser(user.name, user.pass);
ids.users.push(doc._id);
const {
body: result
} = await request.post("/api/v1/auth/login?token=true")
.send({
username: user.name, password: user.pass
}).then();
result.should.have.property("token");
ids.tokens.push(
(await TokensModel.findOne({ token: result.token }).exec())._id
);
user.token = result.token;
});

step("Logout", () => {
return request.post("/api/v1/auth/logout").then();
});

let name = "";
step("Upload Files", async () => {
const {
body: result, status
} = await uploadFiles(request, filepaths);
ids.collections.push(result._id);
} = await request.uploadFiles(filepaths);
status.should.be.eql(201);
result.should.have.properties("name", "_id", "goods");
name = result.name;
Expand Down
22 changes: 7 additions & 15 deletions test/api/system/system.e2e.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,26 @@
import { Model as SystemModel } from "@models/System";
import supertest = require("supertest");
import {
connect, drop
} from "../../helpers/database";
import { connect, drop } from "../../helpers/database";
import { init } from "../../helpers/server";
import auth = require("@db/auth");
import { newName } from "../../helpers/utils";
import { newName, newIds } from "../../helpers/utils";
import { AdminRequest, GuestRequest } from "../../helpers/request";

describe("Collections E2E Api", () => {
describe("System E2E Api", () => {

let request: supertest.SuperTest<supertest.Test>;
let request: AdminRequest;

before(() => {
return connect();
});

const ids = {
users: [ ]
};
const ids = newIds();

after(() => {
return drop(ids);
});

before(async () => {
request = await init();
});

before("login", async () => {
ids.users.push((await auth.login(request))[0]);
request = await new GuestRequest(await init(), ids).login();
});

after(async () => {
Expand Down
3 changes: 1 addition & 2 deletions test/helpers/database/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@ export const newUser = (username?: string, password?: string) => {
export const newUserWithUsergroup = (
username = newName(), password = newName(), gid?: ObjectId
) => {
init();
return usersSvr.addUser({
return init().addUser({
username, password
}, gid);
};
6 changes: 3 additions & 3 deletions test/helpers/files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,16 @@ import faker = require("faker");
import fs = require("fs-extra");
import { sleep } from "./utils";

interface IUploadFileOptions {
export interface IUploadFileOptions {
query?: {
[key: string]: string
};
}

/* tslint:disable:no-empty-interface */
interface IUploadFilesOptions extends IUploadFileOptions { }
export interface IUploadFilesOptions extends IUploadFileOptions { }

const addQuery = (url: string, opts: IUploadFileOptions) => {
export const addQuery = (url: string, opts: IUploadFileOptions) => {
if (opts.query && Object.keys(opts.query).length > 0) {
const query = [ ];
for (const key of Object.keys(opts.query)) {
Expand Down
Loading