express#json TypeScript Examples

The following examples show how to use express#json. 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: index.tsx    From big-web-quiz with Apache License 2.0 6 votes vote down vote up
router.patch(
  '/patch',
  requireSameOrigin(),
  json({ limit: '500kb' }),
  (req, res) => {
    if (!Array.isArray(req.body)) {
      res.status(400).json({ err: 'Expected JSON array.' });
      return;
    }

    try {
      patchState(req.body);
    } catch (err) {
      res.status(400).json({ err: 'Patch failed.' });
      console.error('Patch failed', err);
      return;
    }

    res.status(200).json({ ok: true });
  },
);
Example #2
Source File: index.tsx    From big-web-quiz with Apache License 2.0 6 votes vote down vote up
router.post('/generate-bracket', requireSameOrigin(), json(), (req, res) => {
  try {
    generateBracket(req.body.num || 16);
  } catch (err) {
    console.error('Error generating bracket', err);
    res.status(500).json({ err: 'Error generating bracket' });
    return;
  }

  res.status(200).json({ ok: true });
});
Example #3
Source File: index.tsx    From big-web-quiz with Apache License 2.0 6 votes vote down vote up
wss.on('connection', ws => {
  const interestingState: Partial<State> = {};
  for (const key of interestingStateKeys) {
    // Need to cast to 'any' here as TS isn't smart enough to know key === key.
    interestingState[key] = state[key] as any;
  }

  ws.on('message', data => {
    if (typeof data !== 'string') {
      console.error(`Unexpected client data type`);
      return;
    }

    let json;

    try {
      json = JSON.parse(data);
    } catch (err) {
      console.error(`Couldn't parse client message`);
    }

    if (json.action === 'big-screen-broadcast') {
      bigScreenBroadcast(json.message);
    } else {
      console.error(`Unexpected client action`);
    }
  });

  ws.send(JSON.stringify({ state: interestingState }));
});
Example #4
Source File: test-app.ts    From ironfish-api with Mozilla Public License 2.0 6 votes vote down vote up
export async function bootstrapTestApp(): Promise<INestApplication> {
  const module = await Test.createTestingModule({
    imports: [
      AuthModule,
      ConfigModule.forRoot({
        envFilePath: '.env.test',
        isGlobal: true,
        validationSchema: joi.object({
          API_URL: joi.string().required(),
          BLOCK_EXPLORER_URL: joi.string().required(),
          CHECK_EVENT_OCCURRED_AT: joi.boolean().default(true),
          CHECK_USER_CREATED_AT: joi.boolean().default(true),
          DATABASE_CONNECTION_POOL_URL: joi.string().required(),
          DATABASE_URL: joi.string().required(),
          DATADOG_URL: joi.string().required(),
          DISABLE_FAUCET: joi.boolean().default(false),
          DISABLE_LOGIN: joi.boolean().default(false),
          INCENTIVIZED_TESTNET_URL: joi.string().required(),
          INFLUXDB_API_TOKEN: joi.string().required(),
          INFLUXDB_BUCKET: joi.string().required(),
          INFLUXDB_URL: joi.string().required(),
          IRONFISH_API_KEY: joi.string().required(),
          MAGIC_SECRET_KEY: joi.string().required(),
          NETWORK_VERSION: joi.number().required(),
          NODE_ENV: joi.string().required(),
          NODE_UPTIME_ENABLED: joi.boolean().default(true),
          PORT: joi.number().default(8003),
        }),
      }),
      DatadogModule,
      ...JOBS_MODULES,
      ...REST_MODULES,
    ],
  }).compile();

  const app = module.createNestApplication();
  app.use(json({ limit: '10mb' }));
  return app;
}
Example #5
Source File: app.ts    From monkeytype with GNU General Public License v3.0 6 votes vote down vote up
function buildApp(): express.Application {
  const app = express();

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

  app.set("trust proxy", 1);

  app.use(contextMiddleware);

  addApiRoutes(app);

  app.use(errorHandlingMiddleware);

  return app;
}
Example #6
Source File: server.ts    From express-zod-api with MIT License 5 votes vote down vote up
export function createServer(
  config: ServerConfig & CommonConfig,
  routing: Routing
) {
  const logger = isLoggerConfig(config.logger)
    ? createLogger(config.logger)
    : config.logger;
  const app = express();
  app.disable("x-powered-by");
  const errorHandler = config.errorHandler || defaultResultHandler;
  const compressor = config.server.compression
    ? compression({
        ...(typeof config.server.compression === "object"
          ? config.server.compression
          : {}),
      })
    : undefined;
  const jsonParser = config.server.jsonParser || json();
  const multipartParser = config.server.upload
    ? fileUpload({
        ...(typeof config.server.upload === "object"
          ? config.server.upload
          : {}),
        abortOnLimit: false,
        parseNested: true,
      })
    : undefined;

  const middlewares = ([] as RequestHandler[])
    .concat(compressor || [])
    .concat(jsonParser)
    .concat(multipartParser || []);
  app.use(middlewares);
  app.use(createParserFailureHandler(errorHandler, logger));
  initRouting({ app, routing, logger, config });
  app.use(createNotFoundHandler(errorHandler, logger));

  const httpServer = app.listen(config.server.listen, () => {
    logger.info(`Listening ${config.server.listen}`);
  });

  let httpsServer: https.Server | undefined;
  if (config.https) {
    httpsServer = https
      .createServer(config.https.options, app)
      .listen(config.https.listen, () => {
        logger.info(`Listening ${config.https!.listen}`);
      });
  }

  return { app, httpServer, httpsServer, logger };
}
Example #7
Source File: main.ts    From ironfish-api with Mozilla Public License 2.0 5 votes vote down vote up
async function bootstrap(): Promise<void> {
  const server = express();
  const app = await NestFactory.create<NestExpressApplication>(
    AppModule,
    new ExpressAdapter(server),
  );
  const config = app.get(ApiConfigService);
  const logger = app.get(LoggerService);

  const defaultOrigins = [
    config.get<string>('BLOCK_EXPLORER_URL'),
    config.get<string>('INCENTIVIZED_TESTNET_URL'),
  ];
  const enabledOrigins = config.isStaging()
    ? [
        ...defaultOrigins,
        /localhost/,
        /block-explorer.*\.vercel\.app/,
        /website-testnet.*\.vercel\.app/,
      ]
    : defaultOrigins;

  app.enableCors({
    origin: enabledOrigins,
    methods: 'GET, POST, PUT, OPTIONS',
    allowedHeaders: ['Content-Type', 'Accept', 'Authorization'],
    credentials: true,
  });

  app.use(compression());
  app.use(helmet());
  app.use(json({ limit: '10mb' }));

  const swaggerConfig = new DocumentBuilder()
    .setTitle('Iron Fish API')
    .setDescription('The Rest API to enable public access to Iron Fish data')
    .setVersion('')
    .build();
  const document = SwaggerModule.createDocument(app, swaggerConfig);
  SwaggerModule.setup('docs', app, document, {
    customSiteTitle: 'Iron Fish API Documentation',
  });

  await app.init();

  const port = config.get<number>('PORT');
  logger.info(`Starting API on PORT ${port}`);
  const httpServer = http.createServer(server).listen(port);

  if (module.hot) {
    module.hot.accept();
    module.hot.dispose(() => {
      httpServer.close();
      void app.close();
    });
  }
}
Example #8
Source File: setup-global-middlewares.ts    From clean-architecture-api-boilerplate with MIT License 5 votes vote down vote up
setupGlobalMiddlewares = (app: Application): void => {
  app.use(helmet());
  app.use(json());
}
Example #9
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 #10
Source File: body-parser.ts    From clean-ts-api with GNU General Public License v3.0 5 votes vote down vote up
bodyParser = json()
Example #11
Source File: index.ts    From aero-bot with MIT License 4 votes vote down vote up
export default async function app() {
    const dev = process.env.NODE_ENV !== "production";

    await import("./auth/passport");

    const app = express();

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

    app.use(
        session({
            name: "reserved",
            secret: "some random secret",
            cookie: {
                maxAge: 1000 * 60 * 60 * 24,
                httpOnly: true,
                sameSite: "lax",
                secure: !dev,
            },
            store: MongoStore.create({
                mongoUrl: process.env.mongoPath,
            }),
            saveUninitialized: false,
            resave: false,
        })
    );

    app.use(passport.initialize());
    app.use(passport.session());

    app.get("/", (req, res) => {
        res.send(!!req.user);
    });

    app.get("/commands", (req, res) => {
        res.status(200).send(client.commands);
    });

    app.get("/auth", passport.authenticate("discord"));

    app.get("/auth/redirect", async (req, res, next) => {
        passport.authenticate("discord", async (err, user, info) => {
            if (err) return next(err);

            if (!user) return res.redirect("/auth");

            req.logIn(user, async (err) => {
                if (err) return next(err);

                return res.redirect(
                    `http://aero-ware.github.io/aero-bot/?id=${
                        user._id
                    }&access=${encodeURIComponent(
                        await argon2.hash(
                            Crypto.AES.decrypt(
                                user.accessToken,
                                process.env.CRYPTO_ACCESS!
                            ).toString(Crypto.enc.Utf8)
                        )
                    )}&refresh=${encodeURIComponent(
                        await argon2.hash(
                            Crypto.AES.decrypt(
                                user.refreshToken,
                                process.env.CRYPTO_REFRESH!
                            ).toString(Crypto.enc.Utf8)
                        )
                    )}`
                );
            });
        })(req, res, next);
    });

    app.get("/auth/logout", (req, res) => {
        if (req.user) req.logOut();

        return res.redirect(
            `http://aero-ware.github.io/aero-bot/?id=undefined&access=undefined&refresh=undefined`
        );
    });

    app.post("/verify/", async (req, res) => {
        const { accessToken, refreshToken, id } = req.body;

        if (!accessToken || !refreshToken || !id) return res.sendStatus(400);

        const user = await dashboardUsers.findById(id);

        if (!user) return res.sendStatus(403);

        if (
            !(await argon2.verify(
                accessToken,
                Crypto.AES.decrypt(
                    user.accessToken,
                    process.env.CRYPTO_ACCESS!
                ).toString(Crypto.enc.Utf8)
            )) ||
            !(await argon2.verify(
                refreshToken,
                Crypto.AES.decrypt(
                    user.refreshToken,
                    process.env.CRYPTO_REFRESH!
                ).toString(Crypto.enc.Utf8)
            ))
        )
            return res.sendStatus(403);

        return res.status(200).json({
            avatar: user.avatar,
            username: user.username,
            guilds: user.guilds,
        });
    });

    if (dev) {
        app.listen(80, () =>
            client.logger.success("HTTP Server online on port 80")
        );
    } else {
        const server = https
            .createServer(
                {
                    cert: fs.readFileSync(process.env.SSL_CERT_PATH!),
                    key: fs.readFileSync(process.env.SSL_KEY_PATH!),
                },
                app
            )
            .listen(443);

        server.on("listening", () =>
            client.logger.success(
                // @ts-ignore
                `HTTPS Server online on port ${server.address().port}`
            )
        );
    }
}