express#Express TypeScript Examples

The following examples show how to use express#Express. 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: graphql.ts    From OpenVolunteerPlatform with MIT License 6 votes vote down vote up
createApolloServer = async function (app: Express, config: Config) {
    const db = await connect(config);

    const modelDefs = loadSchemaSync(resolve(__dirname, '../model/main.graphql'), {
        loaders: [
            new GraphQLFileLoader()
        ]
    })

    const { typeDefs, resolvers, contextCreator } = buildGraphbackAPI(modelDefs, {
        serviceCreator: createKeycloakCRUDService(authConfig),
        dataProviderCreator: createMongoDbProvider(db)
    });
    // TODO enable custom resolvers
    const mergedResolvers: any = GMR.merge([resolvers, customResolvers]);
    let apolloConfig: ApolloServerExpressConfig = {
        typeDefs: typeDefs,
        resolvers: mergedResolvers,
        playground: true,
        context: (context) => {
            return {
                ...contextCreator(context),
                db: db
            }
        }
    }

    if (config.keycloakConfig) {
        apolloConfig = buildKeycloakApolloConfig(app, apolloConfig)
    }

    const apolloServer = new ApolloServer(apolloConfig)
    apolloServer.applyMiddleware({ app });

    return apolloServer;
}
Example #2
Source File: groups.ts    From homebridge-zigbee-nt with Apache License 2.0 6 votes vote down vote up
export function mapGroupsRoutes(
  express: Express,
  platform: ZigbeeNTHomebridgePlatform,
  logger: winston.Logger
) {
  express.get<string, any, GroupResponse, any>('/api/groups', (_req, res) => {
    const groups: Group[] = platform.zigBeeClient.getGroups();
    logger.debug('Returning groups: ', groups);
    res.status(constants.HTTP_STATUS_OK);
    res.contentType('application/json');
    res.end(JSON.stringify({ groups: groups.map(group => ({ ID: group.groupID, name: group.meta?.friendlyName })) }));
  });
}
Example #3
Source File: cosmosProxy.ts    From commonwealth with GNU General Public License v3.0 6 votes vote down vote up
function setupCosmosProxy(app: Express, models: DB) {
  // using bodyParser here because cosmjs generates text/plain type headers
  app.post('/cosmosAPI/:chain', bodyParser.text(), async function cosmosProxy(req, res, next) {
    log.trace(`Got request: ${JSON.stringify(req.body, null, 2)}`)
    try {
      log.trace(`Querying cosmos endpoint for chain: ${req.params.chain}`);
      const chain = await models.Chain.findOne({
        where: { id: req.params.chain },
        include: models.ChainNode
      });
      if (!chain) {
        throw new Error('Invalid chain');
      }
      log.trace(`Found cosmos endpoint: ${chain.ChainNode.url}`);
      const response = await axios.post(chain.ChainNode.url, req.body, {
        headers: {
          origin: 'https://commonwealth.im'
        }
      });
      log.trace(`Got response from endpoint: ${JSON.stringify(response.data, null, 2)}`);
      return res.send(response.data);
    } catch (err) {
      res.status(500).json({ message: err.message });
    }
  });
}
Example #4
Source File: setup-async-errors.ts    From clean-architecture-api-boilerplate with MIT License 6 votes vote down vote up
setupAsyncErrors = (app: Express): void => {
  app.use((error: Error, req: Request, res: Response, next: NextFunction) => {
    /* istanbul ignore next */
    if (!error) {
      return next();
    }

    /* istanbul ignore next */
    if (process.env.DEBUG === '1') {
      console.error(error);
    }

    if (!(error instanceof DefaultApplicationError)) {
      return res.status(500).json({
        error: error.name,
        message: 'Something went wrong',
        statusCode: 500,
        messages: ['Something went wrong'],
      });
    }

    return res.status(error.statusCode).json({
      error: error.name,
      message: error.message,
      statusCode: error.statusCode,
      messages: error.messages,
    });
  });
}
Example #5
Source File: zigbee.ts    From homebridge-zigbee-nt with Apache License 2.0 6 votes vote down vote up
export function mapZigBeeRoutes(express: Express, platform: ZigbeeNTHomebridgePlatform) {
  express.get('/api/permitJoin', async (_req, res) => {
    const status = await platform.zigBeeClient.getPermitJoin();
    await platform.zigBeeClient.permitJoin(!status);
    res.status(constants.HTTP_STATUS_OK);
    res.contentType('application/json');
    res.end(JSON.stringify({ permitJoin: status }));
  });

  express.post('/api/permitJoin', async (req, res) => {
    const permitJoin = req.body.permitJoin;
    const status = await platform.zigBeeClient.getPermitJoin();
    if (permitJoin !== status) {
      await platform.zigBeeClient.permitJoin(permitJoin);
      res.status(constants.HTTP_STATUS_OK);
      res.contentType('application/json');
    }
    res.end(JSON.stringify({ permitJoin }));
  });
}
Example #6
Source File: index.ts    From common-ts with MIT License 6 votes vote down vote up
secureExpressApp = (app: Express): void => {
  // This is meant to provide some security across a wide range of
  // attacks. It is mentioned in the express docs under
  // Production Best Practices: Security
  // https://expressjs.com/en/advanced/best-practice-security.html
  // It's not entirely clear that this is helpful
  app.use(helmet())

  // Fix a known bad
  app.use(rejectBadHeaders)
}
Example #7
Source File: endpoint.ts    From ens-metadata-service with MIT License 6 votes vote down vote up
export default function (app: Express) {
  // #swagger.ignore = true
  app.get('/', (_req, res) => {
    res.send('Well done mate To see more go to "/docs"!');
  });

  app.get(
    '/:networkName/:contractAddress(0x[a-fA-F0-9]{40})/:tokenId',
    ensMetadata
  );

  app.get(
    '/:networkName/:contractAddress(0x[a-fA-F0-9]{40})/:tokenId/image',
    ensImage
  );

  app.get(
    '/:networkName/:contractAddress(0x[a-fA-F0-9]{40})/:tokenId/rasterize',
    ensRasterize
  );

  app.get('/:networkName/avatar/:name/meta', avatarMetadata);

  app.get('/:networkName/avatar/:name', avatarImage);

  app.get('/queryNFT', queryNFTep);
}
Example #8
Source File: bind.ts    From homebridge-zigbee-nt with Apache License 2.0 6 votes vote down vote up
export function mapBindRoutes(express: Express, platform: ZigbeeNTHomebridgePlatform): void {
  express.post<string, any, BindUnbindResponse, BindUnbindRequest>('/api/bind', async (req, res) => {
    const bindRequest = req.body;
    const bindingResult = await platform.zigBeeClient.bind(bindRequest.from, bindRequest.to, bindRequest.clusters, bindRequest.sourceEndpoint, bindRequest.targetEndpoint);
    res.status(constants.HTTP_STATUS_OK);
    res.contentType('application/json');
    const result: BindUnbindResponse = {
      data: {
        from: bindRequest.from,
        to: bindRequest.to,
        clusters: bindingResult.successfulClusters,
        failed: bindingResult.failedClusters
      },
      status: 'ok'
    }
    res.end(JSON.stringify(result));
  });

  express.post<string, any, BindUnbindResponse, BindUnbindRequest>('/api/unbind', async (req, res) => {
    const bindRequest = req.body;
    const bindingResult = await platform.zigBeeClient.unbind(bindRequest.from, bindRequest.to, bindRequest.clusters, bindRequest.sourceEndpoint, bindRequest.targetEndpoint);
    res.status(constants.HTTP_STATUS_OK);
    res.contentType('application/json');
    const result: BindUnbindResponse = {
      data: {
        from: bindRequest.from,
        to: bindRequest.to,
        clusters: bindingResult.successfulClusters,
        failed: bindingResult.failedClusters
      },
      status: 'ok'
    }
    res.end(JSON.stringify(result));
  });
}
Example #9
Source File: GithubCreateAppServer.ts    From backstage with Apache License 2.0 6 votes vote down vote up
private async listen(app: Express) {
    return new Promise<string>((resolve, reject) => {
      const listener = app.listen(0, () => {
        const info = listener.address();
        if (typeof info !== 'object' || info === null) {
          reject(new Error(`Unexpected listener info '${info}'`));
          return;
        }
        const { port } = info;
        resolve(`http://localhost:${port}`);
      });
    });
  }
Example #10
Source File: app.ts    From clean-ts-api with GNU General Public License v3.0 6 votes vote down vote up
setupApp = async (): Promise<Express> => {
  const app = express()
  setupStaticFiles(app)
  setupSwagger(app)
  setupMiddlewares(app)
  setupRoutes(app)
  const server = setupApolloServer()
  await server.start()
  server.applyMiddleware({ app })
  return app
}
Example #11
Source File: api.ts    From nouns-monorepo with GNU General Public License v3.0 6 votes vote down vote up
createAPI = (): Express => {
  const app = express();

  app.use(express.json());

  app.get('/', (_req, res) => {
    res.status(200).send({
      message: 'Nouns API Root',
    });
  });

  app.get(
    '/metadata/:tokenId',
    param('tokenId').isInt({ min: 0, max: 1000 }),
    async (req: Request, res) => {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).send({ errors: errors.array() });
      }

      const metadata = await getTokenMetadata(req.params.tokenId);
      if (!metadata) {
        return res.status(500).send({ error: 'Failed to fetch token metadata' });
      }

      res.send(metadata);
    },
  );

  return app;
}
Example #12
Source File: middleware.ts    From snip with MIT License 6 votes vote down vote up
static registerMiddleware(app: Express): void {
    app.enable('trust proxy');
    app.disable('view cache');

    app.use(
      '/api/v1',
      // 20 requests per 10 seconds
      ratelimit({
        windowMs: 10 * 1000,
        max: 20,
      }),
    );

    coreMiddlewares.forEach((middleware) => {
      app.use(middleware);
    });
  }
Example #13
Source File: index.ts    From react-typescript-boilerplate with MIT License 6 votes vote down vote up
/**
 * 配置中间件
 */
export default function setupMiddlewares(server: Express, compiler: Compiler): void {
    // 设置代理
    proxyMiddleware(server);

    // 使用 browserRouter 时,需要重定向所有 html 页面到首页
    server.use(historyFallback());

    // 开发 chrome 扩展的时候可能需要开启跨域,参考:https://juejin.im/post/5e2027096fb9a02fe971f6b8
    server.use(cors());

    // webpack 相关中间件
    server.use(webpackMiddleware(compiler));
}
Example #14
Source File: server.ts    From nouns-monorepo with GNU General Public License v3.0 6 votes vote down vote up
createServer = (app: Express): Server => {
  const server = app.listen(config.serverPort, () => {
    console.info(`HTTP service listening on 0.0.0.0:${config.serverPort}`);
  });

  let connections: Socket[] = [];

  server.on('connection', (connection: Socket) => {
    connections.push(connection);
    connection.on(
      'close',
      () => (connections = connections.filter((curr: Socket) => curr !== connection)),
    );
  });

  const handles = {
    shutdown: () => {
      console.info('Received kill signal, shutting down gracefully');
      server.close(() => {
        console.info('Closed out remaining connections');
        process.exit(0);
      });

      setTimeout(() => {
        console.error('Could not close connections in time, forcefully shutting down');
        process.exit(1);
      }, 10000);

      connections.forEach((curr: Socket) => curr.end());
      setTimeout(() => connections.forEach((curr: Socket) => curr.destroy()), 5000);
    },
  };
  process.on('SIGTERM', handles.shutdown);
  process.on('SIGINT', handles.shutdown);

  return server;
}
Example #15
Source File: config-type.spec.ts    From express-zod-api with MIT License 6 votes vote down vote up
describe("ConfigType", () => {
  describe("createConfig()", () => {
    test("should create a config with server", () => {
      const argument = {
        server: {
          listen: 3333,
        },
        cors: true,
        logger: {
          level: "debug" as const,
          color: false,
        },
      };
      const config = createConfig(argument);
      expect(config).toEqual(argument);
    });

    test("should create a config with app", () => {
      const argument = {
        app: jest.fn() as unknown as Express,
        cors: true,
        logger: {
          level: "debug" as const,
          color: false,
        },
      };
      const config = createConfig(argument);
      expect(config).toEqual(argument);
    });
  });
});
Example #16
Source File: routes.ts    From advanced-node with GNU General Public License v3.0 6 votes vote down vote up
setupRoutes = (app: Express): void => {
  const router = Router()
  readdirSync(join(__dirname, '../routes'))
    .filter(file => !file.endsWith('.map'))
    .map(async file => {
      (await import(`../routes/${file}`)).default(router)
    })
  app.use('/api', router)
}
Example #17
Source File: server.ts    From telefunc with MIT License 6 votes vote down vote up
async function installFrontend(app: Express) {
  if (process.env.NODE_ENV === 'production') {
    const root = __dirname
    app.use(express.static(`${root}/dist/client`))
  } else {
    const vite = await import('vite')
    const viteDevServer = await vite.createServer({
      server: { middlewareMode: 'html' }
    })
    app.use(viteDevServer.middlewares)
  }
}
Example #18
Source File: index.ts    From discord-bot with MIT License 6 votes vote down vote up
export function init(): Express {
  const app = express();

  app.use(express.json());
  app.use(express.urlencoded({ extended: true }));
  app.use(cors());

  app.get('/', (req, res) => {
    res.json(true);
  });

  app.post('/event', (req, res) => {
    const token = req.body['api_token'];

    if (!token || token !== process.env.DISCORD_BOT_API_TOKEN) {
      return res.status(401).json('Wrong API Token.');
    }

    console.log('Event received: ', req.body);

    onEventReceived(req.body);
    return res.json('Event received.');
  });

  app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

  return app;
}
Example #19
Source File: index.ts    From wise-old-man with MIT License 6 votes vote down vote up
setupServices() {
    jobs.init();
    hooks.setup();

    Sentry.init({
      dsn: env.SENTRY_DSN,
      tracesSampleRate: 0.01,
      integrations: [
        new Sentry.Integrations.Http({ tracing: true }),
        new Tracing.Integrations.Express({ app: this.express })
      ]
    });
  }
Example #20
Source File: survey.test.ts    From clean-ts-api with GNU General Public License v3.0 5 votes vote down vote up
app: Express
Example #21
Source File: middlewares.ts    From advanced-node with GNU General Public License v3.0 5 votes vote down vote up
setupMiddlewares = (app: Express): void => {
  app.use(cors())
  app.use(json())
  app.use((req, res, next) => {
    res.type('json')
    next()
  })
}
Example #22
Source File: survey-result.test.ts    From clean-ts-api with GNU General Public License v3.0 5 votes vote down vote up
app: Express
Example #23
Source File: index.ts    From wise-old-man with MIT License 5 votes vote down vote up
express: Express;
Example #24
Source File: body-parser.test.ts    From clean-ts-api with GNU General Public License v3.0 5 votes vote down vote up
app: Express
Example #25
Source File: server.ts    From telefunc with MIT License 5 votes vote down vote up
function start(app: Express) {
  const port = process.env.PORT || 3000
  app.listen(port)
  console.log(`Server running at http://localhost:${port}`)
}
Example #26
Source File: index.ts    From ExpressLRS-Configurator with GNU General Public License v3.0 5 votes vote down vote up
app: Express | undefined;
Example #27
Source File: index.ts    From payload with MIT License 5 votes vote down vote up
express: Express
Example #28
Source File: index.ts    From davinci with MIT License 5 votes vote down vote up
expressApp: Express = express()
Example #29
Source File: api.ts    From Discord-Bot-TypeScript-Template with MIT License 5 votes vote down vote up
private app: Express;