Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
async function bootstrap() {
const app = await NestFactory.create(AppModule, {
cors: true, // 设置跨站访问
logger: false,
});
// 配置api文档信息
const options = new DocumentBuilder()
.setTitle('nestjs api文档')
.setDescription('nestjs api接口文档')
.setBasePath(PREFIX)
.setVersion('1.0')
.addBearerAuth('token')
.setVersion('0.0.1')
.build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup(`${PREFIX}/docs`, app, document);
// 访问频率限制
app.use(
rateLimit({
windowMs: 15 * 60 * 1000, // 15分钟
max: 100, // 限制15分钟内最多只能访问100次
@ApiBearerAuth()
@ApiUseTags('products')
@Controller('products')
export class ProductController {
constructor(
private readonly productService: ProductService,
// private readonly redisService: RedisService
) {}
private readonly logger = new Logger(ProductController.name)
@ApiOperation({ title: 'Get all products' })
@ApiImplicitQuery({ name:'name', type: 'string', description:'product name',required: false})
@ApiResponse({ status: 200, description: 'Return all products.'})
@Get()
async findAll(@Query() query): Promise {
//use redis
// await this.redisService.set('foo','hehe')
// console.log(await this.redisService.get('foo'))
return await this.productService.findAll(query);
}
@ApiOperation({ title: 'Create product' })
@ApiResponse({ status: 201, description: 'The product has been successfully created.'})
@ApiResponse({ status: 403, description: 'Forbidden.' })
@UsePipes(new ValidationPipe({whitelist: true,forbidNonWhitelisted: true }))
@Post()
async create(@Body() productData:CreateProductDto) {
return this.productService.create(productData)
UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { ApiBody, ApiConsumes, ApiOAuth2, ApiOperation, ApiTags } from '@nestjs/swagger';
import { CurrentUser, Roles, RolesEnum } from '../../auth/decorators';
import { CrudController } from '../../core';
import { User } from '../user.entity';
import { CreateProfileDto } from './dto/create-profile.dto';
import { ProfileList } from './dto/profile-list.model';
import { Profile } from './profile.entity';
import { ProfileService } from './profile.service';
// UserModule -> SharedModule -> AuthModule -> UserModule, so
const ALLOWED_MIME_TYPES = ['image/gif', 'image/png', 'image/jpeg', 'image/bmp', 'image/webp'];
@ApiOAuth2(['read'])
@ApiTags('Profile', 'User')
@Controller('profile')
export class ProfileController extends CrudController {
constructor(private readonly profileService: ProfileService) {
super(profileService);
}
@ApiOperation({ summary: 'get CurrentUser Profile' })
@Get('myprofile')
async myProfile(@CurrentUser() user: User): Promise {
console.log('in myprofile', user.profileId);
if (user.profileId) {
// TODO: https://github.com/typeorm/typeorm/issues/1865
return this.profileService.findOne(user.profileId);
} else {
throw new NotFoundException('No Profile Found');
@Get()
async findAll(): Promise {
return this.profileService.findAll();
}
@ApiOperation({ summary: 'Find Profile by id. Admins only' })
@ApiTags('Admin')
@Roles(RolesEnum.ADMIN)
@Get(':id')
async findById(@Param('id', new ParseUUIDPipe({ version: '4' })) id: string): Promise {
console.log('in findById', id);
return this.profileService.findOne(id);
}
@ApiOperation({ summary: 'Create new Profile.' })
@ApiConsumes('multipart/form-data')
// TODO @ApiImplicitFile({ name: 'file', required: true, description: 'Profile Picture' })
// @ApiBody({
// description: 'Profile Picture',
// type: CreateProfileDto,
// })
@UseInterceptors(
FileInterceptor('file', {
fileFilter: (req, file, cb) => {
if (ALLOWED_MIME_TYPES.indexOf(file.mimetype) === -1) {
return cb(
new BadRequestException(
`Error! Incorrect mimetype '${file.mimetype}'. Correct: ${ALLOWED_MIME_TYPES.join(', ')}`,
),
false,
);
}
return this.usersService.createUser({...{userId}, ...userDto});
}
/* Update User */
/*--------------------------------------------*/
@ApiOperation({ title: 'Update User' })
@ApiResponse({ status: 200, description: 'Update User.' })
@Put(':userId')
async updateUser(@Param() userId: UserIdRequestParamsDto, @Body() userDto: UserDto) {
return this.usersService.updateUser({...userId, ...userDto});
}
/* Delete User */
/*--------------------------------------------*/
@ApiOperation({ title: 'Delete User' })
@ApiResponse({ status: 200, description: 'Delete User.' })
@Delete(':userId')
async deleteUser(@Param() userId: UserIdRequestParamsDto) {
return this.usersService.deleteUser(userId);
}
/* TODO: List Users */
/*--------------------------------------------*/
@ApiOperation({ title: 'List Users' })
@ApiResponse({ status: 200, description: 'List Users.' })
@Get()
async findUsers(@Param() param) {
return this.usersService.findUsers();
}
/* TODO: Find User */
/*--------------------------------------------*/
@ApiBearerAuth()
@UseGuards(AuthGuard())
@Post('close') // close -> closechannel
async executeCloseChannel(@Body() dto: PeerNodeDto) {
return await this.ptarmiganService.requestTCP('close', [dto.peerNodeId, '0.0.0.0', 0]);
}
@ApiBearerAuth()
@UseGuards(AuthGuard())
@Post('forceclose') // close -> closechannel
async executeForceCloseChannel(@Body() dto: PeerNodeDto) {
return await this.ptarmiganService.requestTCP('close', [dto.peerNodeId, '0.0.0.0', 0, 'force']);
}
@ApiBearerAuth()
@UseGuards(AuthGuard())
@Post('dev-removechannel/:channelId') // removechannel -> dev-removechannel
async executeRemoveChannel(@Param('channelId') channelId: string) {
return await this.ptarmiganService.requestTCP('removechannel', [channelId]);
}
@ApiBearerAuth()
@UseGuards(AuthGuard())
@Post('resetroutestate') // removechannel -> dev-removechannel
async executeResetRouteState() {
return await this.ptarmiganService.requestTCP('resetroutestate', []);
}
// ------------------------------------------------------------------------------
// payment
// ------------------------------------------------------------------------------
async executeGetLastErrort(@Body() dto: PeerNodeDto) {
return await this.ptarmiganService.requestTCP('getlasterror', [dto.peerNodeId, '0.0.0.0', 0]);
}
@ApiBearerAuth()
@UseGuards(AuthGuard())
@Post('dev-disautoconn') // disautoconn -> dev-disableautoconnect
@ApiImplicitQuery({
name: 'enable',
enum: [0, 1],
})
async executeDisAutoConn(@Query('enable') enable: number) {
return await this.ptarmiganService.requestTCP('disautoconn', [enable.toString(10)]);
}
@ApiBearerAuth()
@UseGuards(AuthGuard())
@Post('dev-listtransactions') // getcommittx -> dev-listtransactions
async executeGetCommitTx(@Body() dto: PeerNodeDto) {
return await this.ptarmiganService.requestTCP('getcommittx', [dto.peerNodeId, '0.0.0.0', 0]);
}
// ------------------------------------------------------------------------------
// channel
// ------------------------------------------------------------------------------
@ApiBearerAuth()
@UseGuards(AuthGuard())
@Post('openchannel') // fund -> openchannel
async executeOpenChannel(@Body() dto: FundDto) {
return await this.ptarmiganService.commandExecuteOpenChannel(dto.peerNodeId, dto.fundingSat, dto.pushMsat, dto.feeratePerKw);
}
async executeListPaymentState(@Body() dto: ListPaymentDto) {
return await this.ptarmiganService.requestTCP('listpayment', [dto.listpayment]);
}
@ApiBearerAuth()
@UseGuards(AuthGuard())
@Post('removepayment') // removepayment -> removepayment
async executeRemovePaymentState(@Body() dto: PaymentIdDto) {
return await this.ptarmiganService.requestTCP('removepayment', [dto.paymentId]);
}
// ------------------------------------------------------------------------------
// fund
// ------------------------------------------------------------------------------
@ApiBearerAuth()
@UseGuards(AuthGuard())
@Post('getwalletinfo') // getnewaddress
async executeGetWalletInfo(): Promise {
return await this.bitcoinService.requestHTTP('getwalletinfo', []);
}
@ApiBearerAuth()
@UseGuards(AuthGuard())
@Post('getnewaddress') // getnewaddress
async executeGetNewAddress(): Promise {
return await this.bitcoinService.requestHTTP('getnewaddress', ['', 'p2sh-segwit']);
}
@ApiBearerAuth()
@UseGuards(AuthGuard())
@Post('listunspent') // listunspent
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableCors({ origin: process.env.CORS_ORIGIN || /codingcoach\.io$/ });
const options = new DocumentBuilder()
.setTitle('Coding Coach')
.setDescription('A REST API for the coding coach platform')
.setVersion('1.0')
.addBearerAuth()
.build();
if (process.env.NODE_ENV !== 'production') {
// We want to get the swagger docs only on development
const document = SwaggerModule.createDocument(app, options);
document.schemes = ['https', 'http'];
fs.writeFileSync('./docs/cc-api-spec.json', JSON.stringify(document));
SwaggerModule.setup('/docs', app, document);
}
await app.listen(process.env.PORT || 3000);
}
bootstrap();
/**
* Init swagger
*/
let documentBuilder = new DocumentBuilder()
.setTitle(config.project.package.name)
.setDescription(config.project.package.description)
.setContactEmail(config.project.package.author.email)
.setExternalDoc('Project on Github', config.project.package.homepage)
.setLicense(config.project.package.license, '')
.setVersion(config.project.package.version)
.addBearerAuth('Authorization', 'header');
documentBuilder = documentBuilder.setSchemes(
config.env.protocol === 'https' ? 'https' : 'http',
config.env.protocol === 'https' ? 'http' : 'https'
);
SwaggerModule.setup('/swagger', app, SwaggerModule.createDocument(app, documentBuilder.build()));
/**
* Start nest application
*/
await app.listen(config.env.port);
/* hmr
if (module.hot) {
module.hot.accept();
module.hot.dispose(() => app.close());
}
*/
}
bootstrap();