dzzzzzy / nestjs-learning Goto Github PK
View Code? Open in Web Editor NEWnestjs 学习教程 :books:,跟我一起学习 nest 框架~ :muscle:
nestjs 学习教程 :books:,跟我一起学习 nest 框架~ :muscle:
This issue provides visibility into Renovate updates and their statuses. Learn more
These updates are currently rate limited. Click on a checkbox below to force their creation now.
These updates have all been created already. Click a checkbox below to force a retry/rebase of any.
@nestjs/common
, @nestjs/core
, @nestjs/passport
, @nestjs/platform-express
)比官网简单易懂
看了package 里面没有 mongo MySQL ,想问一下,这个数据库,是哪里的?
示例文档app.module.ts里面这一行可能需要多添加一些备注,因为自己按照示例demo编写时,这里有点理解不清,
imports: [TypeOrmModule.forRoot(), CatModule], // 导入其他模块的集合
可以备注一下,这里是结合ormconfig.json的typeorm配置的连接数据库的方法
async create(createPostDto: CreatePostDto): Promise<PostEntity> {
return await getManager().transaction(async manager => {
const defaultCover = `https://images.unsplash.com/
photo-1546623235-23f145a669ef?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=900&h=600&fit=crop&ixid=eyJhcHBfaWQiOjF9`;
const postDto: PostDto = {
title: createPostDto.title,
uid: createPostDto.uid,
content: createPostDto.content,
type: createPostDto.type,
status: createPostDto.status,
cover: createPostDto.cover || defaultCover,
subTitle: createPostDto.subTitle || '',
description: createPostDto.description || '',
};
// 保存文章
const post = await manager.save<PostEntity>(
manager.create<PostEntity>(PostEntity, postDto),
);
const postId = post.id;
// ------ 文章分类表
const cids = createPostDto.cids || [];
if (cids.length === 0) {
// 默认未分类
await this.cateRelationService.create({
cid: 14, // 未分类,
composeId: postId,
composeType: SourceType.POST,
});
} else {
const cates = await Promise.all(
_map(cids, cid => {
return this.cateService.findOne(cid);
}),
);
// 过滤不存在的分类
const existCates = _filter(cates, item => !_isUndefined(item));
// 批量插入分类文章映射
// TODO 待优化
const cateRaltions = await Promise.all(
_map(existCates, cate => {
return this.cateRelationService.create({
cid: cate.id,
composeId: postId,
composeType: SourceType.POST,
});
}),
);
}
// -------- 文章标签表
const tagsName = createPostDto.tags || [];
if (tagsName.length) {
// 检测tag是否存在
const tags = await Promise.all(
_map(tagsName, t => {
return this.tagService.findByName(t);
}),
);
// 需要新增的tag
const newTags = [];
const newTagIndex = [];
const existTags: TagEntity[] = [...tags];
_forEach(tags, (tag, index) => {
if (_isUndefined(tag)) { // 为空即是不存在
newTags.push(tagsName[index]);
newTagIndex.push(index);
}
});
// 新增加的tag
const createTags = await Promise.all(
_map(newTags, t => {
return this.tagService.create({ name: t });
}),
);
// 组合获取文章的标签详情数组
_forEach(createTags, (value, index) => {
const existIndex = newTagIndex[index];
existTags[existIndex] = value;
});
// 批量插入标签文章映射
// TODO 待优化
await Promise.all(
_map(existTags, et => {
return this.tagRelationService.create({
tagId: et.id,
composeId: postId,
composeType: SourceType.POST,
});
}),
);
}
return post;
});
}
比如一个博客系统,分为「前端」和「管理端」,使用 Nestjs 来提供 API 服务,「前端」和「管理端」两个端的接口分开管理,,网上找了一圈都没有发现类似的例子,大部分都是两个端的接口混在一起的~
// Aservice
@Injectable
export class Aservice {}
// Acontroller
@Controller()
export class AController {
constructor(private readonly aservice: AService) {} // 这里无法注入
}
// module A
@Module({
controllers: [Acontroller],
providers: [Aservice],
})
export class Amodule {}
// moduleB
@Module({
imports: [Amodule],
})
export class Bmodule {}
// moduleC
@Module({
imports: [Bmodule],
})
export class Cmodule {}
以上会报错
Nest can't resolve dependencies of the AService (?). Please make sure that the argument at index [0] is available in the AModule context
@UseInterceptors(
FileInterceptor('file',{
limits: {
fieldSize: 10,
},
}),
)
async searchImage(@UploadedFile() file, @Body() params) {
const data = file.buffer.toString('base64');
return await this.imageService.imageClassfiy(params.token, data);
}
nestjs上传文件的大小是1m,设置之后报Field value too long,这种情况如何解决。
query.where("entity.id IN (:...ids)", { ids: [1, 2, 3] })
分页的话,还需要查询总条数吧,不然在前端怎么知道有多少页呢,或者是否有下一页呢
程序没有问题,但是在单元测试的时候报错了。
详情可以看 kpfromer/nestjs-typegoose#62
我真的是找遍了文档,尝试了各种的写法,都失败了
CatsSetvice => CatsService
错别字,另外文章写得不错
easy-post项目中的配置为:
"entities": ["src/**/**.entity{.ts,.js}"],
这样连接数据库的时候报错, 而指到
"entities": ["dist/**/**.entity{.ts,.js}"],
就没有问题, 关于这块怎么破?你们没有遇到这个问题么?
我看了一下 handleRequest
这个函数,如果没有认证会直接抛出错误
https://github.com/nestjs/passport/blob/master/lib/auth.guard.ts#L67
然后我设置了全局的拦截器,没有办法拦截
没有进入到 errorinspector 就直接返回了
登录成功后,拿到token,在获取用户列表是带上token,为何还是401?
您好!请问异常过滤器ExceptionFilter只能用于过滤Controller的异常吗?我的服务是Graphql api这种,没有用controller,写了ExceptionFilter没作用。我看您例子graphql api里用了拦截器ErrorsInterceptor,有异常的话return Promise.resolve({
code: 500,
message: 出现了意外错误:${error.toString()}
});
但是我照这样写,在sayHello方法里故意抛出一个HttpException异常,客户端调用Query.sayHello方法时,收到的却是code为INTERNAL_SERVER_ERROR的异常,消息是"Expected Iterable, but did not find one for field Query.sayHello.",还包含其他stacktrace等信息,不是我想要的那种简单异常信息,请问是我用法不对吗?
看了官方的 auth 例子,看懂了,但还是不太知道怎么融入进项目里
另外,博主的文章写得很棒,我刚开始学 nest 框架,你关于 Module 的介绍那篇让明白不少东西,感谢
参照Nestjs CRUD Restful API Demo示例,自己编写时,发现缺少Nestjs-Learning/demo/rest-api/src/common/下面errors.interceptor.ts和result.interface.ts两文件的说明,期望作者能够更新这两个文件说明。
export class RabbitController {
@Client({
transport: Transport.RMQ,
options: {
urls: ['amqp://guest:[email protected]'],
queue: 'payment_service_queue',
queueOptions: { durable: true },
},
})
orderClient: ClientProxy;
@Get('order')
async sendorder() {
await this.orderClient.send<string>({ cmd: 'order' }, 'order').toPromise();
}
@MessagePattern({ cmd: 'order' })
order(data: string) {
clg('Server got: ' + data);
}
}
目前我只会这样用,官方文档什么都没说都不知道参数意思 比如 send第一个参数 是否还有其他命令?
@MessagePattern({ cmd: 'order' }) 接收到消息后如果处理异常了怎么办?
如何发送ack说明处理完成?
如何消息分发多个消费者?
Exchange 交换器如何使用?
等等很多东西文档都没有。
需要测试分页查询中,添加了左连接之后,(skip、take) 和 (offset、limit) 对 getMany 和 getRowMany 的结果集的影响。
/**
* 获得对象数组
* 函数后的冒号标识初始化项目定义类型,约束为Cat数组
*
* @copyright 问鼎公司 版权所有
* @author Wending <[email protected]>
* @return {Cat[]} [description]
*/
async findAll(): Promise<Cat[]> {
return this.cats;
}
Nestjs-Learning/demo/rest-api at master · dzzzzzy/Nestjs-Learning
中的这一段:
@Controller()
export class AppController {
/**
* 构造函数,用于注入这个类的依赖,注入类时,需要使用 @Inject() 修饰符,其参数是被注入的类的类名
*/
constructor(
@Inject(AppService) private readonly appService: AppService,
) { }
我看官方文档中没有使用@Inject(AppService)
这句呀
是我理解错什么了吗
发现很多graphql很多教程都只有graphql部分,
然后auth都只有auth部分。
然后grahpql部分没问题,
auth restful部分也没问题。
但是graphql加 auth几各种问题了
請問TypeORM的createQueryBuilder的groupBy時,可以像MYSQL將date格式用DATE_FORMAT轉為YYYY-MM-DD作為groupBy嗎?
在完成例子的时候没有安装PostgreSql,就想更换为sqlite3. npm i --save sqlite3
,修改配置如下。
在运行时提示不能在项目外导入模块。查资料说是因为程序在运行时从src编译到了dist,因此把entity从src修改到了dist之后可以正常使用。
还想更换为mongodb但是显示没有成功,可能因为跟案例里面的自增id有关,有机会可以再测试一下。
{
"type": "sqlite",
"database": "./mydb.sql",
"entities": [
"dist/**/**.entity{.ts,.js}"
],
"synchronize": true,
"logging": true
}
安装模块,运行rest-api,会出现错误: Error: Cannot find module 'graphql/utilities/buildASTSchema'
另外提一下,package.json缺失了@nestjs/graphql模块
我是挺喜欢这个框架的
能不能在文档中提两句? 官方文档没举例子
谢谢
apollo-server 在 2.x 版本中改变了很多 API,并且不兼容 1.x 版本。
目前 nest 官方只提供了 express 和 fastify 作为 web层的框架,但 apollo-server 官方只提供了对 express 的支持,所以需要用 apollo-server-express
这个包的 2.x 版本写一个 nest-graphql
入门例子。
@Injectable()
export class RolesGuard implements CanActivate {
constructor(
@Inject(Reflector) private readonly reflector: Reflector,
@Inject(UserRoleService) private readonly userRoleService: UserRoleService,
) {}
}
守卫没有module,所以对于如何注入service好迷茫....
我把这个守卫变成了全局的守卫也没有用
providers: [
{
provide: APP_GUARD,
useClass: RolesGuard,
},
]
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.