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 README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Store Box
# StoreBox-Api

Store PandoraBox Firmware Images and its packages

Expand Down
8 changes: 5 additions & 3 deletions TODOLIST.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@
- [x] 上传到指定Categroy
- [x] 上传时追加Catogroy
- [x] 整顿collectin info的goods 列表
- [ ] Token 使用日志显示
- [ ] Good 下载次数统计
- [ ] 接入统计
- [ ] 统计
- [ ] Token 使用日志显示
- [ ] 用户登录记录
- [x] Good 下载次数统计
- [ ] 接入统计
- [x] 配置文件写入初始化用户账号密码
- [ ] 接入AuthBox
- [x] Redis 接入
Expand Down
2 changes: 1 addition & 1 deletion src/express.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import connectRedis = require("connect-redis");
import { config } from "@utils/config";
import helmet = require("helmet");

import { error } from "./modules/common/middlewares/logger.middleware";
import { error } from "./middlewares/logger.middleware";
import { isTest } from "@utils/env";

const RedisStore = connectRedis(session);
Expand Down
27 changes: 27 additions & 0 deletions src/models/Log.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { model, SchemaDefinition, Model as M } from "mongoose";
import { Base, IDoc, IDocRaw } from "./common";
import newCache = require("@utils/newCache");

const Definition: SchemaDefinition = {
key: { type: String, required: true },
type: { type: String, required: true },
ua: { type: String, required: true },
ipaddr: { type: String, required: true }
};

export interface ILogs extends IDocRaw {
key: string;
type: string;
ua: string;
ipaddr: string;
}

export const FLAG = "logs";

export const cache = newCache(FLAG);

const Schema = new Base(Definition).createSchema();

export type LogDoc = IDoc<ILogs>;

export const Model: M<LogDoc> = model(FLAG, Schema);
2 changes: 1 addition & 1 deletion src/modules/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Module, MiddlewaresConsumer } from "@nestjs/common";
// Modules
import { DatabaseModule } from "./database/database.module";
import {controllers, ControllersModule} from "./controllers.module";
import { NoCacheMiddleware } from "./common/middlewares/noCache.middleware";
import { NoCacheMiddleware } from "../middlewares/noCache.middleware";

@Module({
modules: [ DatabaseModule, ControllersModule ]
Expand Down
17 changes: 13 additions & 4 deletions src/modules/collections/collections.admin.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { CollectionDoc } from "@models/Collection";
import { ObjectId } from "@models/common";
import { RolesGuard } from "@guards/roles";
import { CollectionsService } from "@services/collections";
import { LogsService } from "@services/logs";
import { UtilService } from "@services/util";
import { Roles } from "@decorators/roles";
import { ParseIntPipe } from "@pipes/parse-int";
Expand All @@ -27,7 +28,10 @@ import {
// endregion Swagger Docs
export class CollectionsAdminController {

constructor(private readonly collectionsSvr: CollectionsService) { }
constructor(
private readonly collectionsSvr: CollectionsService,
private readonly logsSvr: LogsService
) { }

private async getCollectionsRes(uid: ObjectId, query: PerPageDto) {
const arr = await this.collectionsSvr.list(uid, {
Expand Down Expand Up @@ -102,12 +106,17 @@ export class CollectionsAdminController {
@ApiOperation({ title: "Get One Collection's Info" })
// endregion Swagger Docs
public async getCollection(@Param() param: CCidDto) {
const obj = await this.collectionsSvr.getById(param.cid);
const obj = await this.collectionsSvr.getObjectById(param.cid);
if (!obj) {
return null;
}
obj.goods = UtilService.toListRespone(obj.goods as any[], {
perNum: obj.goods.length
const goods = [ ];
for (const good of obj.goods) {
good.downloaded = await this.logsSvr.goodDownloadCount(good._id);
goods.push(good);
}
obj.goods = UtilService.toListRespone(goods, {
perNum: goods.length
}) as any;
return obj;
}
Expand Down
28 changes: 17 additions & 11 deletions src/modules/collections/collections.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { Roles } from "@decorators/roles";
import { GetCollectionNameDto } from "./collections.dto";
import { PerPageDto } from "@dtos/page";
import { ParseIntPipe } from "@pipes/parse-int";
import { LogsService } from "@services/logs";

@UseGuards(RolesGuard)
@Controller("/collections")
Expand All @@ -17,7 +18,10 @@ import { ParseIntPipe } from "@pipes/parse-int";
// endregion Swagger Docs
export class CollectionsController {

constructor(private readonly collectionsSvr: CollectionsService) { }
constructor(
private readonly collectionsSvr: CollectionsService,
private readonly logsSvr: LogsService
) { }

@Roles("guest")
@Get("/:name")
Expand All @@ -29,25 +33,27 @@ export class CollectionsController {
@Param() param: GetCollectionNameDto,
@Query(new ParseIntPipe()) query: PerPageDto
) {
const doc = await this.collectionsSvr.getByName(param.name);
const doc = await this.collectionsSvr.getObjectByName(param.name);
if (!doc) {
return null;
}
let obj;
obj = doc.toObject();
obj.creator = obj.creator.nickname;
obj.goods.map((good) => {
const obj = doc;
// obj = doc.toObject();
obj.creator = obj.creator.nickname as any;
const goods = [ ];
for (const good of obj.goods) {
const keys = [
"__v", "uploader", "hidden"
];
for (const key of keys) {
delete good[key];
}
return good;
});
obj.goods = UtilService.toListRespone(obj.goods, {
perNum: obj.goods.length
});
good.downloaded = await this.logsSvr.goodDownloadCount(good._id);
goods.push(good);
}
obj.goods = UtilService.toListRespone(goods, {
perNum: goods.length
}) as any;
return obj;
}

Expand Down
11 changes: 6 additions & 5 deletions src/modules/controllers.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,14 @@ import { SystemController } from "./system/system.controller";
// region Middlewares
import {
UploadFileMiddleware, UploadFilesMiddleware
} from "./common/middlewares/upload.middleware";
} from "../middlewares/upload.middleware";
import {
ApiLoggerMiddleware, DownloadLoggerMiddleware
} from "./common/middlewares/logger.middleware";
import { RolesMiddleware } from "./common/middlewares/roles.middleware";
} from "../middlewares/logger.middleware";
import { RolesMiddleware } from "../middlewares/roles.middleware";
import {
ReloadSessionMiddleware
} from "./common/middlewares/reloadSession.middleware";
} from "../middlewares/reloadSession.middleware";
// endregion Middlewares

// region Services
Expand All @@ -40,6 +40,7 @@ import { UsergroupsService } from "@services/usergroups";
import { SystemService } from "@services/system";
import { CategoriesService } from "@services/categories";
import { GoodsService } from "@services/goods";
import { LogsService } from "@services/logs";
// endregion Services

export const controllers = [
Expand All @@ -56,7 +57,7 @@ export const controllers = [
export const services = [
RegexpsService, CategoriesService, GoodsService,
CollectionsService, TokensService, UsersService, UsergroupsService,
SystemService
SystemService, LogsService
];

@Module({
Expand Down
7 changes: 6 additions & 1 deletion src/modules/files/files.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { Roles } from "@decorators/roles";
import { RolesGuard } from "@guards/roles";
import { ParseIntPipe } from "@pipes/parse-int";
import { GoodsService } from "@services/goods";
import { LogsService } from "@services/logs";

import { Response } from "express";
import pathExists = require("path-exists");
Expand All @@ -26,7 +27,10 @@ import { DownlaodDto } from "./files.dto";
@ApiUseTags("Good Download")
export class FilesController {

constructor(private readonly goodsSvr: GoodsService) { }
constructor(
private readonly goodsSvr: GoodsService,
private readonly logsSvr: LogsService
) { }

@Roles("guest")
@Get("/categories/:cid/goods/:id")
Expand All @@ -52,6 +56,7 @@ export class FilesController {
if (!good.active) {
throw new BadRequestException("Disallow download the File");
}
await this.logsSvr.stepGoodDownloadCount(params.id, req);
res.download(filepath, good.originname, (err) => {
/* istanbul ignore if */
if (err) {
Expand Down
11 changes: 8 additions & 3 deletions src/modules/files/goods.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ import { GoodsService } from "@services/goods";
import { CategoriesService } from "@services/categories";
import { Roles } from "@decorators/roles";
import { ParseIntPipe } from "@pipes/parse-int";
import { ToArrayPipe } from "@pipes/to-array";
import { ListResponse, DEF_PER_COUNT } from "@dtos/page";
import { LogsService } from "@services/logs";
import { reduce } from "lodash";

import { GoodsQueryDto } from "./goods.dto";
Expand All @@ -22,7 +24,8 @@ export class GoodsController {

constructor(
private readonly goodsSvr: GoodsService,
private readonly categoriesSvr: CategoriesService
private readonly categoriesSvr: CategoriesService,
private readonly logsSvr: LogsService
) { }

@Roles("guest")
Expand All @@ -32,7 +35,9 @@ export class GoodsController {
@ApiOperation({ title: "Get Good List" })
@ApiResponse({ status: HttpStatus.OK, type: ListResponse })
// endregion Swagger Docs
public async getList(@Query(new ParseIntPipe()) query: GoodsQueryDto) {
public async getList(
@Query(new ParseIntPipe(), new ToArrayPipe("tags")) query: GoodsQueryDto
) {
const categoryModels = await this.categoriesSvr.getByTags(query.tags);
const categories = reduce(categoryModels, (obj, cate) => {
obj[cate._id.toString()] = cate;
Expand All @@ -41,7 +46,6 @@ export class GoodsController {
if (Object.keys(categories).length === 0) {
return UtilService.toListRespone([ ]);
}
const perNum = query.perNum || DEF_PER_COUNT;

const cids = Object.keys(categories);
const goods =
Expand All @@ -56,6 +60,7 @@ export class GoodsController {
good.attributes = Array.from(new Set(
good.attributes.concat(category.attributes)
)) as any;
good.downloaded = this.logsSvr.goodDownloadCount(good._id);
return good;
});
return UtilService.toListRespone(goods, Object.assign({
Expand Down
9 changes: 6 additions & 3 deletions src/modules/goods/goods.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import { isArray } from "util";
import { CreateValueDto, EditValueDto } from "../values/values.dto";
import { GoodAttributeParamDto, UploadQueryDto, EditBodyDto } from "./goods.dto";
import { RegexpCountCheckInterceptor } from "@interceptors/regexp-count-check";
import { LogsService } from "@services/logs";

@UseGuards(RolesGuard)
@Controller("api/v1/goods")
Expand All @@ -47,7 +48,8 @@ export class GoodsAdminController {
private readonly collectionsSvr: CollectionsService,
private readonly regexpSvr: RegexpsService,
private readonly categoriesSvr: CategoriesService,
private readonly goodsSvr: GoodsService
private readonly goodsSvr: GoodsService,
private readonly logsSvr: LogsService
) { }

private toMd5sum(filepath: string) {
Expand Down Expand Up @@ -233,7 +235,7 @@ export class GoodsAdminController {
});
const collection =
isArray(collections) ? collections[0] : collections;
return this.collectionsSvr.getById(collection._id, {
return this.collectionsSvr.getObjectById(collection._id, {
populate: [ "goods" ]
});
}
Expand All @@ -248,13 +250,14 @@ export class GoodsAdminController {
public async get(@Param() param: GidDto) {
let obj;
try {
obj = await this.goodsSvr.getById(param.gid, {
obj = await this.goodsSvr.getObjectById(param.gid, {
populate: [
"attributes",
{ path: "uploader", select: "nickname" },
{ path: "category", select: "name attributes tags" }
]
});
obj.downloaded = await this.logsSvr.goodDownloadCount(param.gid);
} catch (error) {
throw new BadRequestException(error.toString());
}
Expand Down
10 changes: 5 additions & 5 deletions src/services/collections.service.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Component, Param, BadRequestException } from "@nestjs/common";
import { UidDto } from "@dtos/ids";
import {
Model as CollectionsModel, cache, ICollections
Model as CollectionsModel, cache, ICollections, ICollectionsRaw
} from "@models/Collection";
import { ObjectId } from "@models/common";
import { DEF_PER_COUNT } from "@dtos/page";
Expand Down Expand Up @@ -51,10 +51,10 @@ export class CollectionsService extends BaseService<ICollections> {
* Get By Collection Name
* @param name Collection Name
*/
public getByName(name: string, opts = this.GET_OPTIONS) {
public getObjectByName(name: string, opts = this.GET_OPTIONS) {
return this.loadAndCache(
`getByName_${name}`,
() => this.findObject({ name }, opts),
() => this.findObject({ name }, opts) as Promise<ICollectionsRaw>,
1000
);
}
Expand All @@ -63,10 +63,10 @@ export class CollectionsService extends BaseService<ICollections> {
* Get By Collection ID
* @param id Collection ID
*/
public getById(id: ObjectId, opts = this.GET_OPTIONS) {
public getObjectById(id: ObjectId, opts = this.GET_OPTIONS) {
return this.loadAndCache(
`getById_${id.toString()}`,
() => this.findObjectById(id, opts),
() => this.findObjectById(id, opts) as Promise<ICollectionsRaw>,
1000
);
}
Expand Down
8 changes: 8 additions & 0 deletions src/services/goods.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,14 @@ export class GoodsService extends BaseService<IGoods> {
return super.findById(id, opts);
}

/**
* Get Good by Good ID
* @param id Good ID
*/
public getObjectById(id: ObjectId, opts?: IGetOptions) {
return super.findObjectById(id, opts);
}

/**
* Edit Good by Good ID
* @param id Good ID
Expand Down
Loading