How to use @nestjs/platform-express - 10 common examples

To help you get started, we’ve selected a few @nestjs/platform-express examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github xmlking / ngx-starter-kit / apps / api / src / app / user / profile / profile.controller.ts View on Github external
@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,
          );
        }
        cb(null, true);
      },
      limits: {
        fileSize: 1024000,
      },
    }),
  )
github TimurRK / nestjs-example / src / main.ts View on Github external
async function bootstrap() {
  const server = express();

  const app = await NestFactory.create(AppModule, new ExpressAdapter(server));

  app.use(helmet());
  app.use(cookieParser());
  app.enableCors(corsOptions);

  app.useGlobalPipes(
    new ValidationPipe({
      transform: true,
    })
  );

  // tslint:disable-next-line: no-unsafe-any
  app.useWebSocketAdapter(new WsAdapter(app));

  app.use('/voyager', voyagerMiddleware({ endpointUrl: '/graphql' }));
github joe307bad / points / API.Points / src / user / user.controller.ts View on Github external
} from '../core/acl';
import { UploadFileSettings } from '../app.settings';
import {OnlyApprovedUsers} from '../auth/guards/approved.guard';

const resource = 'user';
const to = (action: ApiAction) =>
  new ApiPermission(action, resource, 'id', 'objectId');
// resource specific action like 'login-as' or 'approve-achievement-for'

@Controller(resource)
@UseGuards(PermissionGaurd)
export class UserController implements IUserService {
  constructor(private readonly user: UserService) {}

  @Post()
  @UseInterceptors(FileInterceptor('photo', UploadFileSettings))
  async create(
    @Body() user: UserDto,
    @UploadedFile() photo
  ): Promise {
    user.photo = photo ? photo.filename : null;
    return await this.user.create(user).catch(err => err);
  }

  @Post('login')
  async login(@Body() user: UserDto): Promise {
    return await this.user.login(user).catch(err => err);
  }

  @Get('exists/:userName')
  async exists(@Param() user: { userName: string }): Promise {
    return await this.user.exists(user).catch(err => err);
github danielwii / asuna-node-server / src / modules / core / uploader / controller.ts View on Github external
* @param files
   */
  @ApiBearerAuth()
  @ApiOperation({ summary: 'Upload files' })
  @ApiConsumes('multipart/form-data')
  @ApiQuery({
    name: 'local',
    enum: ['1'],
    required: false,
    description: 'force use local storage',
  })
  @UseGuards(AnyAuthGuard)
  @Post()
  @UseInterceptors(
    // new FastifyFileInterceptor('files'),
    FilesInterceptor('files', configLoader.loadNumericConfig(ConfigKeys.UPLOADER_MAX_COUNT, 3), fileInterceptorOptions),
  )
  async uploader(
    @Query('bucket') bucket = '',
    @Query('prefix') prefix = '',
    @Query('local') local: string, // 是否使用本地存储
    @Req() req: AnyAuthGuard,
    @UploadedFiles() files,
  ): Promise {
    /*
    if (req.fileValidationError) {
      throw new UploadException(req.fileValidationError);
    } */
    logger.log(`upload files ${r({ bucket, prefix, files })}`);
    const results = await this.saveFiles(bucket, prefix, local, files).catch(error => {
      logger.error(`upload files ${r({ bucket, prefix, files })} error: ${r(error)}`);
      // fs.rmdir(tempFolder).catch(reason => logger.warn(r(reason)));
github bs32g1038 / node-blog / server / modules / upload / upload.service.ts View on Github external
import path from 'path';
import multr from 'multer';
import { Model } from 'mongoose';
import { Injectable, BadRequestException } from '@nestjs/common';
import { MulterModule } from '@nestjs/platform-express';
import { InjectModel } from '../../utils/model.util';
import { FileDocument, FileModel } from '../../models/file.model';
import { MediaDocument, MediaModel } from '../../models/media.model';
import { md5 } from '../../utils/crypto.util';
import { creteUploadFile } from '../../utils/upload.util';

MulterModule.register({
    storage: multr.memoryStorage(),
});

@Injectable()
export class UploadService {
    public constructor(
        @InjectModel(FileModel) private readonly fileModel: Model,
        @InjectModel(MediaModel) private readonly mediaModel: Model
    ) {}

    public async uploadSingalImage(file: Express.Multer.File) {
        // 实体数据
        const originalName = file.originalname;
        const mimetype: string = file.mimetype;
        const size = file.size;
        const suffix = path.extname(file.originalname);
github visual-knight / platform-community-edition / apps / api / src / index.ts View on Github external
function bootstrapServer(): Promise {
  const expressApp = express();
  const adapter = new ExpressAdapter(expressApp);
  return NestFactory.create(AppModule, adapter)
    .then(app => app.enableCors())
    .then(app => app.init())
    .then(() => serverless.createServer(expressApp));
}
github rdlabo / serverless-nestjs / src / index.ts View on Github external
function bootstrapServer(): Promise {
  const expressApp = express();
  const adapter = new ExpressAdapter(expressApp);
  return NestFactory.create(AppModule, adapter)
    .then(app => app.enableCors())
    .then(app => app.init())
    .then(() => serverless.createServer(expressApp));
}
github magishift / magishift.core / packages / keycloak / src / handler.ts View on Github external
async function bootstrapServer(): Promise {
  if (!cachedServer) {
    try {
      const expressApp = require('express')();

      const adapter = new ExpressAdapter(expressApp);

      const nestApp = await NestFactory.create(KeycloakModule, adapter);

      nestApp.use(eventContext());
      await nestApp.init();

      cachedServer = createServer(expressApp, undefined, binaryMimeTypes);
    } catch (error) {
      return Promise.reject(error);
    }
  }
  return Promise.resolve(cachedServer);
}
github theodo / nestjs-serverless-demo / src / lambda.ts View on Github external
async function bootstrapServer(): Promise {
 if (!cachedServer) {
    const expressApp = express();
    const nestApp = await NestFactory.create(AppModule, new ExpressAdapter(expressApp))
    nestApp.use(eventContext());
    await nestApp.init();
    cachedServer = createServer(expressApp, undefined, binaryMimeTypes);
 }
 return cachedServer;
}
github bazelbuild / rules_nodejs / examples / nestjs / src / main.ts View on Github external
export async function bootstrap(port: number): Promise {
  const app = await NestFactory.create(AppModule, new ExpressAdapter());
  await app.listen(port);
  Logger.log(`Application served at http://localhost:${port}`);
  return app;
}

@nestjs/platform-express

Nest - modern, fast, powerful node.js web framework (@platform-express)

MIT
Latest version published 4 days ago

Package Health Score

95 / 100
Full package analysis

Similar packages