http#Server TypeScript Examples
The following examples show how to use
http#Server.
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: utils.ts From budget-node with GNU General Public License v3.0 | 7 votes |
export function buildProdServer(port: number, callback: () => void): Server {
const app = express();
app.use(session(config.sessionConfig));
app.use(morgan(config.morganPattern, { stream: config.morganStream }));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(passport.initialize());
app.use(cors());
app.use(errorHandler());
app.use(logger.initialize());
app.use(routes);
return app.listen(port, () => {
console.log('started production-like server on port: ' + port);
callback();
});
}
Example #2
Source File: app.ts From paystring with Apache License 2.0 | 6 votes |
/**
* Boots up the public API to respond to PayID Protocol requests.
*
* @param appConfig - The application configuration to boot up the Express server with.
*
* @returns An HTTP server listening on the public API port.
*/
private launchPublicApi(appConfig: typeof config.app): Server {
this.publicApiExpress.use('/', publicApiRouter)
return this.publicApiExpress.listen(appConfig.publicApiPort, () =>
logger.info(`Public API listening on ${appConfig.publicApiPort}`),
)
}
Example #3
Source File: E2ETestEnvironment.ts From ADR-Gateway with MIT License | 6 votes |
TestServices:{
adrDbConn?: Promise<Connection>
adrServer?: {port:number,server:Server}
softwareProduct?: {port:number,server:Server}
adrJwks?: {port:number,server:Server}
adrGateway?: {port:number,server:Server,connectivity:DefaultConnector}
mockRegister?: {port:number,server:Server},
mockDhServer?: {port:number,server:Server},
httpsProxy?:{
mockRegister?: {port:number,server:Server}
adrServer?: {port:number,server:Server}
adrGateway?: {port:number,server:Server}
mockDhServer?: {port:number,server:Server}
mockDhServerMTLS?: {port:number,server:Server}
}
}
Example #4
Source File: standaloneServer.ts From backstage with Apache License 2.0 | 6 votes |
export async function startStandaloneServer(
options: ServerOptions,
): Promise<Server> {
const logger = options.logger.child({ service: 'airbrake-backend' });
const config = await loadBackendConfig({ logger, argv: process.argv });
const airbrakeConfig = extractAirbrakeConfig(config);
logger.debug('Starting application server...');
const router = await createRouter({
logger,
airbrakeConfig,
});
let service = createServiceBuilder(module)
.setPort(options.port)
.addRouter('/api/airbrake', router);
if (options.enableCors) {
logger.info('CORS is enabled, limiting to localhost with port 3000');
service = service.enableCors({ origin: 'http://localhost:3000' });
} else {
logger.info('CORS is disabled, allowing all origins');
service = service.enableCors({ origin: '*' });
}
return await service.start().catch(err => {
logger.error(err);
process.exit(1);
});
}
Example #5
Source File: verify-budget.pact.ts From budget-node with GNU General Public License v3.0 | 6 votes |
describe('Budget Api provider verification', () => {
const port = 8080;
let app: Express;
let server: Server;
let givenRequest: (req: Request) => void;
beforeAll((done) => {
app = express();
app.use(express.json());
app.use((req: Request, _res: Response, next: NextFunction) => {
givenRequest(req);
next();
});
app.use(new DashboardController(new InMemoryBudgetRepository()).getRouter());
server = app.listen(port, () => done());
});
afterAll(() => server.close());
it('passes for the all interactions', async () => {
givenRequest = (req) => {
req.user = { accountId: '1' };
}
const options = {
providerBaseUrl: 'http://localhost:8080',
pactUrls: [path.resolve(__dirname, './../../pacts/budgetclient-budgetprovider.json')],
// we can also point here to the Pact Broker to get the contracts
}
await new Verifier(options).verifyProvider();
});
});
Example #6
Source File: oauthClientServer.spec.ts From cli with Apache License 2.0 | 6 votes |
mockedCreateServer.mockImplementation((listener?: RequestListener) => {
const req = {
url: '/?code=TheCode&state=TheState',
} as unknown as IncomingMessage;
const res = {end: jest.fn()} as unknown as ServerResponse;
process.nextTick(() => listener && listener(req, res));
return {
listen: mockedServerListen,
close: mockedServerClose,
} as unknown as Server;
});
Example #7
Source File: server.ts From typescript.service.boilerplate with MIT License | 6 votes |
runServer = (port: number = 4000): Server => {
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(APIDOC_ROUTE, swaggerServe, swaggerSetup(swaggerDocument));
app.use(manifestRoutes);
return app.listen(port, () => logger.info(`Service running on port ${port} ...`));
}
Example #8
Source File: next-fixture.ts From dendron with GNU Affero General Public License v3.0 | 6 votes |
test = base.extend<{
port: string;
}>({
port: [
// eslint-disable-next-line no-empty-pattern
async ({}, use) => {
const app = next({
dev: false,
dir: path.resolve(__dirname, ".."),
});
await app.prepare();
const handle = app.getRequestHandler();
// start next server on arbitrary port
const server: Server = await new Promise((resolve) => {
const server = createServer((req, res) => {
if (req.url) {
const parsedUrl = parse(req.url, true);
handle(req, res, parsedUrl);
}
});
server.listen((error: any) => {
if (error) throw error;
resolve(server);
});
});
// get the randomly assigned port from the server
const port = String((server.address() as AddressInfo).port);
// provide port to tests
await use(port);
},
{
//@ts-ignore
scope: "worker",
},
],
})
Example #9
Source File: apiHooks.test.ts From bee-dashboard with BSD 3-Clause "New" or "Revised" License | 6 votes |
export function mockServer(data: Record<string | number | symbol, string>): Promise<Server> {
const app = express()
app.use(cors())
app.get('/info', (req, res) => {
res.send(data)
})
return new Promise(resolve => {
const server = app.listen(() => {
resolve(server)
})
})
}
Example #10
Source File: cheque-mock.ts From swarm-cli with BSD 3-Clause "New" or "Revised" License | 6 votes |
/**
* Starts a mock HTTP server with predefined cheque responses.
*
* Can be run in standalone mode:
* ts-node test/http-mock/cheque-mock.ts run 1333
*/
export function createChequeMockHttpServer(port: number): Server {
const server = createServer((request, response) => {
response.writeHead(200, { 'Content-Type': 'application/json' })
if (request.url === '/health') {
response.end(JSON.stringify(health))
}
if (request.url === '/topology') {
response.end(JSON.stringify(topology))
}
if (request.url === '/chequebook/cheque') {
response.end(JSON.stringify(lastCheques))
}
if (request.url === '/chequebook/balance') {
response.end(JSON.stringify(balance))
}
if (request.url === '/chequebook/cashout/1105536d0f270ecaa9e6e4347e687d1a1afbde7b534354dfd7050d66b3c0faad') {
response.end(JSON.stringify(lastCashoutCheque1))
}
if (request.url === '/node') {
response.end(JSON.stringify(nodeInfo))
}
})
server.listen(port)
return server
}
Example #11
Source File: farrow-server.test.ts From farrow with MIT License | 6 votes |
describe('Farrow', () => {
beforeEach(() => {
shell.cd(projectPath)
})
it('should build and run a server', async () => {
shell.rm('-rf', distPath)
expect(shell.test('-d', distPath)).toBe(false)
const result = await exec(`npm run build`)
console.log('result.stderr', {
stderr: result.stderr,
distPath,
})
expect(result.code).toBe(0)
expect(shell.test('-d', distPath)).toBe(true)
const { server } = require(distPath).default as { http: HttpPipeline; server: Server }
await request(server)
.get('/user/123')
.expect(200, {
user: {
id: 123,
},
})
await request(server).get('/env/NODE_ENV').expect(200, {
NODE_ENV: 'test',
})
})
})
Example #12
Source File: server.ts From cardano-rosetta with Apache License 2.0 | 6 votes |
buildServer = (
services: Services,
cardanoCli: CardanoCli,
cardanoNode: CardanoNode,
logLevel: string,
extraParameters: ExtraParams
): fastify.FastifyInstance<Server, IncomingMessage, ServerResponse> => {
const server = fastify({ logger: { level: logLevel }, bodyLimit: getBodyLimit() });
const { networkId, pageSize, mock, disableSearchApi } = extraParameters;
if (!mock) server.register(metricsPlugin, { endpoint: '/metrics' });
server.register(fastifyBlipp);
server.register(openapiGlue, {
specification: `${__dirname}/openApi.json`,
service: Controllers.configure(services, cardanoCli, cardanoNode, pageSize, disableSearchApi),
noAdditional: true
});
// Custom error handling is needed as the specified by Rosetta API doesn't match
// the fastify default one
server.setErrorHandler((error: Error, request, reply) => {
let toSend = error;
request.log.error(error, '[errorHandler] An error ocurred and will be sent as response');
if (error instanceof ApiError === false) {
toSend = ErrorFactory.unspecifiedError(`An error occurred for request ${request.id}: ${error.message}`);
}
// rosseta-go-sdk always returns 500
reply.status(StatusCodes.INTERNAL_SERVER_ERROR).send({ ...toSend, message: toSend.message });
});
return server;
}
Example #13
Source File: index.ts From l2beat with MIT License | 6 votes |
async function main() {
const app = express()
app.use(express.static('build'))
const server = await new Promise<Server>((resolve) => {
const server = app.listen(1234, () => resolve(server))
})
const slugs = projects.map((x) => x.slug).concat('overview', 'jobs')
const browser = await puppeteer.launch()
await Promise.all(slugs.map(screenshot))
async function screenshot(slug: string) {
const page = await browser.newPage()
await page.setViewport({
width: 600,
height: 314,
deviceScaleFactor: 2,
})
const path = `build/meta-images/${slug}.png`
const url = `http://localhost:1234/meta-images/${slug}`
await page.goto(url, { waitUntil: 'networkidle0' })
await page.screenshot({ path })
console.log(`Captured ${path}`)
}
await browser.close()
await new Promise<void>((resolve, reject) =>
server.close((err) => (err ? reject(err) : resolve()))
)
}
Example #14
Source File: lambda-main.ts From mamori-i-japan-api with BSD 2-Clause "Simplified" License | 6 votes |
bootstrapServer = async (): Promise<Server> => {
const expressApp = express()
const adapter = new ExpressAdapter(expressApp)
const app = await NestFactory.create(AppModule, adapter, {
logger: false,
})
app.useLogger(new AppLogger())
app.use(RequestIdMiddleware)
app.use(eventContext())
app.enableCors()
await app.init()
return createServer(expressApp)
}
Example #15
Source File: cat-tenancy.spec.ts From nestjs-tenancy with MIT License | 6 votes |
describe('CatTenancy', () => {
let server: Server;
let app: INestApplication;
beforeEach(async () => {
const module = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = module.createNestApplication();
server = app.getHttpServer();
await app.init();
});
it(`should return created document`, (done) => {
const createDto = { name: 'Nest', breed: 'Maine coon', age: 5 };
request(server)
.post('/cats')
.set('X-TENANT-ID', 'cats')
.send(createDto)
.expect(201)
.end((err, { body }) => {
expect(body.name).toEqual(createDto.name);
expect(body.age).toEqual(createDto.age);
expect(body.breed).toEqual(createDto.breed);
done();
});
});
afterEach(async () => {
await app.close();
});
});
Example #16
Source File: server.ts From nouns-monorepo with GNU General Public License v3.0 | 6 votes |
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 #17
Source File: index.test.ts From lighthouse-audit-service with Apache License 2.0 | 6 votes |
describe('server exports', () => {
describe('#startServer', () => {
let server: Server;
let port: number;
beforeEach(async () => {
port = await getPort();
server = await startServer({ port });
});
afterEach(async () => {
await new Promise(resolve => server.close(() => resolve(true)));
});
it('exposes a _ping endpoint', async () => {
await request(`http://localhost:${port}`).get(`/_ping`).expect(200);
});
});
describe('#getApp', () => {
it('exposes a _ping endpoint', async () => {
const app = express();
const las = await getApp();
app.use('/', las);
await request(app)
.get(`/_ping`)
.expect(200)
.then(() => {
expect(() => las.get('connection').end()).not.toThrow();
});
});
});
});
Example #18
Source File: server.ts From storage-api with Apache License 2.0 | 6 votes |
(async () => {
const { isMultitenant } = getConfig()
if (isMultitenant) {
await runMultitenantMigrations()
await listenForTenantUpdate()
const adminApp: FastifyInstance<Server, IncomingMessage, ServerResponse> = buildAdmin({
logger,
})
try {
await adminApp.listen(5001, '0.0.0.0')
} catch (err) {
adminApp.log.error(err)
process.exit(1)
}
} else {
await runMigrations()
}
const app: FastifyInstance<Server, IncomingMessage, ServerResponse> = build({
logger,
exposeDocs,
})
app.listen(5000, '0.0.0.0', (err, address) => {
if (err) {
console.error(err)
process.exit(1)
}
console.log(`Server listening at ${address}`)
})
})()
Example #19
Source File: terminus.ts From hubble-contracts with MIT License | 6 votes |
terminus = (node: HubbleNode, server: Server) => {
createTerminus(server, {
// https://github.com/godaddy/terminus#how-to-set-terminus-up-with-kubernetes
beforeShutdown: async () => sleep(5000),
onSignal: async () => {
console.log("shutting down");
await node.close();
},
onShutdown: async () => {
console.log("shutdown complete");
},
healthChecks: {
"/health": async () => {
// no-op, HTTP 200
}
}
});
}
Example #20
Source File: index.ts From sendight-backend with GNU General Public License v3.0 | 6 votes |
initSocket = (server: Server): void => {
const io = new SocketServer(server, {
cors: {
origin: '*',
},
serveClient: false,
});
io.on('connection', (socket: Socket): void => {
roomSocket(io, socket);
roomLeaveSocket(io, socket);
offerSocket(io, socket);
answerSocket(io, socket);
iceCandidateSocket(io, socket);
});
}
Example #21
Source File: health-check.ts From server with GNU General Public License v3.0 | 6 votes |
/**
* Creates a Health Check Service When the Server is Terminating
*
* @param {Server} server - Http Server Object
*/
function healthCheck(server: Server): void {
const options: TerminusOptions = {
onSignal,
onShutdown,
};
createTerminus(server, options);
}
Example #22
Source File: screenReaderMock.ts From Assistive-Webdriver with MIT License | 5 votes |
useScreenReaderMock = () => {
const host = "127.0.0.1";
let server: Server;
let port: number;
let app: WebSocket.Server;
const urlMap = new WeakMap<WebSocket, string>();
beforeAll(async () => {
server = createServer();
app = new WebSocket.Server({ server });
app.on("connection", (ws, req) => urlMap.set(ws, req.url!));
server.listen(0, host);
await new Promise((resolve, reject) =>
server.on("listening", resolve).on("error", reject)
);
port = (server.address() as AddressInfo).port;
});
afterAll(async () => {
await new Promise(resolve => server.close(resolve));
await new Promise(resolve => app.close(resolve));
});
return {
sendScreenReaderMessage(message: string) {
app.clients.forEach(client => client.send(message));
},
getScreenReaderClients() {
const clients: string[] = [];
app.clients.forEach(client => clients.push(urlMap.get(client)!));
return clients;
},
getScreenReaderTCPRedirection(
vmPort = DEFAULT_VM_PORT_SCREENREADER
): PortRedirection {
return {
hostAddress: host,
hostPort: port,
vmPort
};
}
};
}
Example #23
Source File: graphql-server.ts From graphql-eslint with MIT License | 5 votes |
private server: Server;
Example #24
Source File: server.ts From mockiavelli with MIT License | 5 votes |
server: Server
Example #25
Source File: app.spec.ts From bootcamp-devops-lemoncode with MIT License | 5 votes |
server: Server
Example #26
Source File: app.ts From The-TypeScript-Workshop with MIT License | 5 votes |
private server: Server;
Example #27
Source File: app.ts From paystring with Apache License 2.0 | 5 votes |
private publicApiServer?: Server
Example #28
Source File: E2ETestEnvironment.ts From ADR-Gateway with MIT License | 5 votes |
Stop = async () => {
const PromiseToClose = (testService?: {server:Server}) => {
return new Promise((resolve,reject) => {
if (typeof testService?.server != 'undefined')
testService.server.close((err) => {
if (err) reject(err);
resolve();
})
})
}
let httpsAdrGatewayClosed = PromiseToClose(this.TestServices.httpsProxy?.adrGateway)
let httpsAdrServerClosed = PromiseToClose(this.TestServices.httpsProxy?.adrServer)
let httpsMockDhServerClosed = PromiseToClose(this.TestServices.httpsProxy?.mockDhServer)
let httpsMockDhServerMTLSClosed = PromiseToClose(this.TestServices.httpsProxy?.mockDhServerMTLS)
let httpsMockRegisterClosed = PromiseToClose(this.TestServices.httpsProxy?.mockRegister)
let adrServerClosed = PromiseToClose(this.TestServices.adrServer)
let mockRegisterClosed = PromiseToClose(this.TestServices.mockRegister)
let mockDhServerClosed = PromiseToClose(this.TestServices.mockDhServer)
let adrGatewayClosed = PromiseToClose(this.TestServices.adrGateway)
let mockSoftwareProductClosed = PromiseToClose(this.TestServices.softwareProduct)
let adrJwksClosed = PromiseToClose(this.TestServices.adrJwks)
let dbClosed = new Promise((resolve,reject) => {
if (typeof this.TestServices.adrDbConn != 'undefined') {
this.TestServices.adrDbConn.then(conn => conn.close().then(() => {
logger.debug("Closed database")
resolve()
},(err) => {
logger.debug("Error closing database")
reject(err)
}))
} else {
return Promise.resolve()
}
})
await adrGatewayClosed;
await adrServerClosed;
await mockSoftwareProductClosed;
await adrJwksClosed;
await mockDhServerClosed;
await mockRegisterClosed;
await httpsAdrGatewayClosed;
await httpsAdrServerClosed;
await httpsMockDhServerClosed;
await httpsMockDhServerMTLSClosed;
await httpsMockRegisterClosed;
await dbClosed;
return;
}
Example #29
Source File: index.ts From Dimensions with MIT License | 5 votes |
private server: Server;