express-serve-static-core#Request TypeScript Examples

The following examples show how to use express-serve-static-core#Request. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: http-server.ts    From homebridge-zigbee-nt with Apache License 2.0 6 votes vote down vote up
function middleware(publicURL: string, logger: winston.Logger) {
  function logAccessIfVerbose(req) {
    const protocol = req.connection.encrypted ? 'https' : 'http';
    const fullUrl = `${protocol}://${req.headers.host}${req.url}`;

    logger.debug(`Request: ${fullUrl}`);
  }

  return function (req: Request, res: Response, next: NextFunction) {
    logAccessIfVerbose(req);

    function send404() {
      if (next) {
        return next();
      }
      setHeaders(res);
      res.writeHead(404);
      res.end();
    }

    function sendIndex() {
      req.url = `/${path.basename('index.html')}`;
      serve(req, res, send404);
    }

    const { pathname } = url.parse(req.url);
    if (pathname.startsWith('/api')) {
      next();
    } else if (!pathname.startsWith(publicURL) || path.extname(pathname) === '') {
      // If the URL doesn't start with the public path, or the URL doesn't
      // have a file extension, send the main HTML bundle.
      return sendIndex();
    } else {
      // Otherwise, serve the file from the dist folder
      req.url = pathname.slice(publicURL.length);
      return serve(req, res, sendIndex);
    }
  };
}
Example #2
Source File: index.ts    From node-express-typescript with MIT License 6 votes vote down vote up
app.use(function(req:Request, res: Response, next:NextFunction) {

    if(!fs.existsSync(frontEndPath+req.path) && allRoutes.filter(r => req.path.startsWith(r)).length < 1){
        console.log('redirect:',req.path)
        res.sendFile(frontEndPath + 'index.html');
    } else {
        next()
    }

});
Example #3
Source File: auth.ts    From node-express-typescript with MIT License 6 votes vote down vote up
protected = (req: Request, res: Response, next: NextFunction) => {
        const authHeader = req.header('Authorization');
        if (authHeader) {
            const token = authHeader.split(' ')[1];
            const jwt: AuthObject = this.decode(token);
            if (jwt) {
                console.log(jwt)
                req.user = jwt;
                next();
            }
        }
        if(typeof req.user === 'undefined'){
            res.status(401).json({error: 'unauthorized'}).end();
        }
    }
Example #4
Source File: resolver.ts    From node-express-typescript with MIT License 6 votes vote down vote up
update = async (req: Request, res: Response) => {
        res.json(await this.model.update(req.body))
    }
Example #5
Source File: app.imports.ts    From api with GNU Affero General Public License v3.0 5 votes vote down vote up
imports = [
  ConsoleModule,
  HttpModule.register({
    timeout: 5000,
    maxRedirects: 10,
  }),
  ServeStaticModule.forRoot({
    rootPath: join(__dirname, '..', 'public'),
    exclude: ['/graphql'],
  }),
  ConfigModule.forRoot({
    load: [
      () => {
        return {
          LOCALES_PATH: join(process.cwd(), 'locales'),
          SECRET_KEY: process.env.SECRET_KEY || crypto.randomBytes(20).toString('hex'),
        }
      },
    ],
  }),
  JwtModule.registerAsync({
    imports: [ConfigModule],
    inject: [ConfigService],
    useFactory: (configService: ConfigService): JwtModuleOptions => ({
      secret: configService.get<string>('SECRET_KEY'),
      signOptions: {
        expiresIn: '4h',
      },
    }),
  }),
  LoggerModule.forRoot(LoggerConfig),
  GraphQLModule.forRoot<ApolloDriverConfig>({
    debug: process.env.NODE_ENV !== 'production',
    definitions: {
      outputAs: 'class',
    },
    driver: ApolloDriver,
    sortSchema: true,
    introspection: process.env.NODE_ENV !== 'production',
    playground: process.env.NODE_ENV !== 'production',
    installSubscriptionHandlers: true,
    autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
    // to allow guards on resolver props https://github.com/nestjs/graphql/issues/295
    fieldResolverEnhancers: [
      'guards',
      'interceptors',
    ],
    resolverValidationOptions: {

    },
    context: ({ req, connection }) => {
      if (!req && connection) {
        const headers: IncomingHttpHeaders = {}

        Object.keys(connection.context).forEach(key => {
          headers[key.toLowerCase()] = connection.context[key]
        })

        return {
          req: {
            headers,
          } as Request,
        }
      }

      return { req }
    },
  }),
  TypeOrmModule.forRootAsync({
    imports: [ConfigModule],
    inject: [ConfigService],
    useFactory: (configService: ConfigService): TypeOrmModuleOptions => {
      const type: any = configService.get<string>('DATABASE_DRIVER', 'sqlite')
      let migrationFolder: string
      let migrationsTransactionMode: 'each' | 'none' | 'all' = 'each'

      switch (type) {
        case 'cockroachdb':
        case 'postgres':
          migrationFolder = 'postgres'
          break

        case 'mysql':
        case 'mariadb':
          migrationFolder = 'mariadb'
          break

        case 'sqlite':
          migrationFolder = 'sqlite'
          migrationsTransactionMode = 'none'
          break

        default:
          throw new Error('unsupported driver')
      }

      return ({
        name: 'ohmyform',
        synchronize: false,
        type,
        url: configService.get<string>('DATABASE_URL'),
        database: type === 'sqlite' ? configService.get<string>('DATABASE_URL', 'data.sqlite').replace('sqlite://', '') : undefined,
        ssl: configService.get<string>('DATABASE_SSL', 'false') === 'true' ? { rejectUnauthorized: false } : false,
        entityPrefix: configService.get<string>('DATABASE_TABLE_PREFIX', ''),
        logging: configService.get<string>('DATABASE_LOGGING', 'false') === 'true',
        entities,
        migrations: [`${__dirname}/**/migrations/${migrationFolder}/**/*{.ts,.js}`],
        migrationsRun: configService.get<boolean>('DATABASE_MIGRATE', true),
        migrationsTransactionMode,
      })
    },
  }),
  TypeOrmModule.forFeature(entities),
  MailerModule.forRootAsync({
    imports: [ConfigModule],
    inject: [ConfigService],
    useFactory: (configService: ConfigService) => ({
      transport: configService.get<string>('MAILER_URI', 'smtp://localhost:1025'),
      defaults: {
        from: configService.get<string>('MAILER_FROM', 'OhMyForm <no-reply@localhost>'),
      },
    }),
  }),
]
Example #6
Source File: resolver.ts    From node-express-typescript with MIT License 5 votes vote down vote up
get = async (req: Request, res: Response) => {
        const id = req.params.id || req.user.userId;
        res.json(await this.model.get(id));
    }
Example #7
Source File: resolver.ts    From node-express-typescript with MIT License 5 votes vote down vote up
getAll = async (req: Request, res: Response) => {
        res.json(await this.model.find());
    }
Example #8
Source File: resolver.ts    From node-express-typescript with MIT License 5 votes vote down vote up
create = async (req: Request, res: Response) => {
        res.json(await this.model.create(req.body))
    }