http#createServer TypeScript Examples
The following examples show how to use
http#createServer.
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.ts From Uptimo with MIT License | 6 votes |
app.prepare().then(async() => {
createServer((req, res) => {
const parsedUrl = parse(req.url!, true)
handle(req, res, parsedUrl)
}).listen(port);
const { ping } = await import('../lib/pinger');
ping();
// tslint:disable-next-line:no-console
console.log(
`> Server listening at http://localhost:${port} as ${
dev ? 'development' : process.env.NODE_ENV
}`
)
})
Example #2
Source File: index.ts From lerna-monorepo-typescript-example with MIT License | 6 votes |
app.prepare().then(() => {
createServer((req, res) => {
const parsedUrl = parse(req.url!, true);
const { pathname, query } = parsedUrl;
if (pathname === '/') {
app.render(req, res, '/', query);
} else {
handle(req, res, parsedUrl);
}
}).listen(port);
logger(
`> Server listening at http://localhost:${port} as ${
dev ? 'development' : process.env.NODE_ENV
}`,
);
});
Example #3
Source File: next-entry.ts From malagu with MIT License | 6 votes |
app.prepare().then(() => {
createServer(async (req, res) => {
try {
const parsedUrl = parse(req.url, true)
await handle(req, res, parsedUrl)
} catch (err) {
console.error('Error occurred handling', req.url, err)
res.statusCode = 500
res.end('internal server error')
}
}).listen(port, () => {
console.log(`> Ready on http://${hostname}:${port}`)
})
})
Example #4
Source File: webServer.ts From Aragorn with MIT License | 6 votes |
protected openWebServer(webserverPort: number, isInit = false) {
const app = express();
app.use(express.json());
app.get('/', (_, res) => {
res.send('Aragorn WebServer is running');
});
app.post('/', multer().array('files'), async (req: any, res) => {
const data = await this.handleUpload(req?.files || req.body?.files);
res.json({
url: data[0] || '',
urls: data
});
});
this.server = createServer(app);
this.server.on('error', (err: Error & { code: string }) => {
if (err.code === 'EADDRINUSE') {
console.error('webserver open failed, webserver port is used');
if (!isInit) {
Ipc.sendMessage('toggle-webserver-reply', { toggle: true, success: false, message: err.message });
}
}
this.server?.close();
});
this.server.listen(webserverPort, '127.0.0.1', () => {
console.log('webserver open success');
if (!isInit) {
this.setting.configuration.openWebServer = true;
this.setting.configuration.webServerPort = webserverPort;
this.setting.save();
Ipc.sendMessage('toggle-webserver-reply', { toggle: true, success: true });
Ipc.sendMessage('setting-configuration-get-reply', this.setting.configuration);
}
});
}
Example #5
Source File: server.ts From eufy-security-ws with MIT License | 6 votes |
async start(): Promise<void> {
this.server = createServer();
this.wsServer = new WebSocketServer({ server: this.server });
this.sockets = new ClientsController(this.driver, this.logger);
this.wsServer.on("connection", (socket, request) => this.sockets?.addSocket(socket, request));
this.logger.debug(`Starting server on host ${this.options.host}, port ${this.options.port}`);
this.server.on("error", this.onError.bind(this));
this.server.listen(this.options.port, this.options.host);
await once(this.server, "listening");
this.emit("listening");
this.logger.info(`Eufy Security server listening on host ${this.options.host}, port ${this.options.port}`);
await this.driver.connect()
}
Example #6
Source File: server.ts From amman with Apache License 2.0 | 6 votes |
private static createApp(
ammanState: AmmanState,
accountProvider: AccountProvider,
accountPersister: AccountPersister,
snapshotPersister: AccountPersister,
accountStates: AccountStates,
knownLabels: Record<string, string>
) {
const server = createServer()
const io = new Server(server, {
cors: {
origin: '*',
},
})
const relayServer = new RelayServer(
io,
ammanState,
accountProvider,
accountPersister,
snapshotPersister,
accountStates,
knownLabels
)
return { app: server, io, relayServer }
}
Example #7
Source File: index.ts From TXQ with MIT License | 6 votes |
async function startServer() {
let app = await createExpress();
let server = createServer(app);
app.get('/', function(req, res) {
res.json({
hello: 'world'
});
});
server.listen(Config.api.port);
console.log('Listening on', Config.api.port);
process.on('unhandledRejection', handleExceptions);
process.on('uncaughtException', handleExceptions);
process.on('SIGINT', handleServerExit('SIGINT', server));
process.on('SIGTERM', handleServerExit('SIGTERM', server));
return app;
}
Example #8
Source File: server.ts From slot-game with MIT License | 6 votes |
createServer(async (req, res) => {
const url = req.url === "/" ? "/index.html" : req.url;
const filePath = join(STATIC_PATH, `${url}`);
try {
const data = await fs.readFile(filePath);
res.end(data);
} catch (err) {
res.statusCode = 404;
res.end(`File "${url}" is not found`);
}
}).listen(PORT, () => console.log(`Static on port ${PORT}`));
Example #9
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 #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: oauthClientServer.ts From cli with Apache License 2.0 | 5 votes |
public startServer(port: number, hostname: string, expectedState: string) {
let server: Server;
const serverPromise = new Promise<{accessToken: string}>(
(resolve, reject) => {
const listener = async (req: IncomingMessage, res: ServerResponse) => {
try {
const {code, state} = this.parseUrl(req);
const {tokenEndpoint} = this.authServiceConfig;
if (!state || !code) {
return;
}
if (state !== expectedState) {
throw new InvalidStateError(state, expectedState);
}
const data = this.getTokenQueryString(code);
const authRequest = await axios.post<AccessTokenResponse>(
tokenEndpoint,
data,
this.requestConfig
);
const accessToken = authRequest.data.access_token;
res.end('Close your browser to continue');
resolve({accessToken});
} catch (error: unknown) {
reject(error);
} finally {
server.close();
}
};
server = createServer(listener);
server.listen(port, hostname);
}
);
return serverPromise;
}
Example #12
Source File: server.ts From cli with Apache License 2.0 | 5 votes |
public constructor(port: number) {
this.server = createServer((req: IncomingMessage, res: ServerResponse) => {
res.end(`port ${port} taken`);
}).listen(port);
}
Example #13
Source File: service.ts From one-platform with MIT License | 5 votes |
httpServer = createServer(app)
Example #14
Source File: index.ts From uno-game with MIT License | 5 votes |
static http = createServer(Server.app)
Example #15
Source File: HttpServer.ts From nodetskeleton with MIT License | 5 votes |
constructor(appWrapper: AppWrapper) {
this.#appWrapper = appWrapper;
this.server = createServer(this.#appWrapper.app);
}
Example #16
Source File: inspector-util.ts From stacks-blockchain-api with GNU General Public License v3.0 | 5 votes |
export async function startProfilerServer(
httpServerPort?: number | string
): Promise<{
server: Server;
address: string;
close: () => Promise<void>;
}> {
let serverPort: number | undefined = undefined;
if (httpServerPort !== undefined) {
serverPort = parsePort(httpServerPort);
}
const app = express();
let existingSession:
| { instance: ProfilerInstance<unknown>; response: express.Response }
| undefined;
app.get(
'/profile/cpu',
asyncHandler(async (req, res) => {
if (existingSession) {
res.status(409).json({ error: 'Profile session already in progress' });
return;
}
const durationParam = req.query['duration'];
const seconds = Number.parseFloat(durationParam as string);
if (!Number.isFinite(seconds) || seconds < 0) {
res.status(400).json({ error: `Invalid 'duration' query parameter "${durationParam}"` });
return;
}
const samplingIntervalParam = req.query['sampling_interval'];
let samplingInterval: number | undefined;
if (samplingIntervalParam !== undefined) {
samplingInterval = Number.parseFloat(samplingIntervalParam as string);
if (!Number.isInteger(samplingInterval) || samplingInterval < 0) {
res.status(400).json({
error: `Invalid 'sampling_interval' query parameter "${samplingIntervalParam}"`,
});
return;
}
}
const cpuProfiler = initCpuProfiling(samplingInterval);
existingSession = { instance: cpuProfiler, response: res };
try {
const filename = `cpu_${Math.round(Date.now() / 1000)}_${seconds}-seconds.cpuprofile`;
res.setHeader('Cache-Control', 'no-store');
res.setHeader('Transfer-Encoding', 'chunked');
res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.flushHeaders();
await cpuProfiler.start();
const ac = new AbortController();
const timeoutPromise = timeout(seconds * 1000, ac);
await Promise.race([timeoutPromise, once(res, 'close')]);
if (res.writableEnded || res.destroyed) {
// session was cancelled
ac.abort();
return;
}
const result = await cpuProfiler.stop();
const resultString = JSON.stringify(result);
logger.info(
`[CpuProfiler] Completed, total profile report JSON string length: ${resultString.length}`
);
res.end(resultString);
} finally {
const session = existingSession;
existingSession = undefined;
await session?.instance.dispose().catch();
}
})
);
let neonProfilerRunning: boolean = false;
app.get(
'/profile/cpu/start',
asyncHandler(async (req, res) => {
if (existingSession) {
res.status(409).json({ error: 'Profile session already in progress' });
return;
}
const samplingIntervalParam = req.query['sampling_interval'];
let samplingInterval: number | undefined;
if (samplingIntervalParam !== undefined) {
samplingInterval = Number.parseFloat(samplingIntervalParam as string);
if (!Number.isInteger(samplingInterval) || samplingInterval < 0) {
res.status(400).json({
error: `Invalid 'sampling_interval' query parameter "${samplingIntervalParam}"`,
});
return;
}
}
const cpuProfiler = initCpuProfiling(samplingInterval);
existingSession = { instance: cpuProfiler, response: res };
await cpuProfiler.start();
const profilerRunningLogger = setInterval(() => {
if (existingSession) {
logger.error(`CPU profiler has been enabled for a long time`);
} else {
clearInterval(profilerRunningLogger);
}
}, 10_000).unref();
res.end('CPU profiler started');
})
);
app.get('/profile/native/cpu/start', (req, res) => {
if (neonProfilerRunning) {
res.status(500).end('error: profiler already started');
return;
}
neonProfilerRunning = true;
try {
const startResponse = startProfiler();
console.log(startResponse);
res.end(startResponse);
} catch (error) {
console.error(error);
res.status(500).end(error);
}
});
app.get('/profile/native/cpu/stop', (req, res) => {
if (!neonProfilerRunning) {
res.status(500).end('error: no profiler running');
return;
}
neonProfilerRunning = false;
let profilerResults: Buffer;
try {
profilerResults = stopProfiler();
} catch (error: any) {
console.error(error);
res.status(500).end(error);
return;
}
const fileName = `profile-${Date.now()}.svg`;
res.setHeader('Cache-Control', 'no-store');
res.setHeader('Transfer-Encoding', 'chunked');
res.setHeader('Content-Disposition', `attachment; filename="${fileName}"`);
res.setHeader('Content-Type', 'image/svg+xml');
res.status(200).send(profilerResults);
});
app.get(
'/profile/cpu/stop',
asyncHandler(async (req, res) => {
if (!existingSession) {
res.status(409).json({ error: 'No profile session in progress' });
return;
}
if (existingSession.instance.sessionType !== 'cpu') {
res.status(409).json({ error: 'No CPU profile session in progress' });
return;
}
try {
const elapsedSeconds = existingSession.instance.stopwatch.getElapsedSeconds();
const timestampSeconds = Math.round(Date.now() / 1000);
const filename = `cpu_${timestampSeconds}_${elapsedSeconds}-seconds.cpuprofile`;
const result = await (existingSession.instance as ProfilerInstance<inspector.Profiler.Profile>).stop();
const resultString = JSON.stringify(result);
logger.info(
`[CpuProfiler] Completed, total profile report JSON string length: ${resultString.length}`
);
res.setHeader('Cache-Control', 'no-store');
res.setHeader('Transfer-Encoding', 'chunked');
res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
res.setHeader('Content-Type', 'application/json; charset=utf-8');
// await new Promise<void>(resolve => res.end(resultString, () => resolve()));
res.end(resultString);
} finally {
const session = existingSession;
existingSession = undefined;
await session?.instance.dispose().catch();
}
})
);
app.get(
'/profile/heap_snapshot',
asyncHandler(async (req, res) => {
if (existingSession) {
res.status(409).json({ error: 'Profile session already in progress' });
return;
}
const filename = `heap_${Math.round(Date.now() / 1000)}.heapsnapshot`;
const tmpFile = path.join(os.tmpdir(), filename);
const fileWriteStream = fs.createWriteStream(tmpFile);
const heapProfiler = initHeapSnapshot(fileWriteStream);
existingSession = { instance: heapProfiler, response: res };
try {
res.setHeader('Cache-Control', 'no-store');
res.setHeader('Transfer-Encoding', 'chunked');
res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.flushHeaders();
// Taking a heap snapshot (with current implementation) is a one-shot process ran to get the
// applications current heap memory usage, rather than something done over time. So start and
// stop without waiting.
await heapProfiler.start();
const result = await heapProfiler.stop();
logger.info(
`[HeapProfiler] Completed, total snapshot byte size: ${result.totalSnapshotByteSize}`
);
await pipelineAsync(fs.createReadStream(tmpFile), res);
} finally {
const session = existingSession;
existingSession = undefined;
await session?.instance.dispose().catch();
try {
fileWriteStream.destroy();
} catch (_) {}
try {
logger.info(`[HeapProfiler] Cleaning up tmp file ${tmpFile}`);
fs.unlinkSync(tmpFile);
} catch (_) {}
}
})
);
app.get(
'/profile/cancel',
asyncHandler(async (req, res) => {
if (!existingSession) {
res.status(409).json({ error: 'No existing profile session is exists to cancel' });
return;
}
const session = existingSession;
await session.instance.stop().catch();
await session.instance.dispose().catch();
session.response.destroy();
existingSession = undefined;
await Promise.resolve();
res.json({ ok: 'existing profile session stopped' });
})
);
const server = createServer(app);
const serverSockets = new Set<Socket>();
server.on('connection', socket => {
serverSockets.add(socket);
socket.once('close', () => {
serverSockets.delete(socket);
});
});
await new Promise<void>((resolve, reject) => {
try {
server.once('error', error => {
reject(error);
});
server.listen(serverPort, '0.0.0.0', () => {
resolve();
});
} catch (error) {
reject(error);
}
});
const addr = server.address();
if (addr === null) {
throw new Error('server missing address');
}
const addrStr = typeof addr === 'string' ? addr : `${addr.address}:${addr.port}`;
logger.info(`Started profiler server on: http://${addrStr}`);
const closeServer = async () => {
const closePromise = new Promise<void>((resolve, reject) => {
if (!server.listening) {
// Server already closed (can happen when server is shared between cluster workers)
return resolve();
}
server.close(error => (error ? reject(error) : resolve()));
});
for (const socket of serverSockets) {
socket.destroy();
}
await closePromise;
};
return { server, address: addrStr, close: closeServer };
}
Example #17
Source File: server.ts From ledokku with MIT License | 5 votes |
http = createServer(app)
Example #18
Source File: server.ts From metroline with GNU General Public License v3.0 | 5 votes |
async function main(): Promise<any> {
await AppDb.init();
await migrate(AppDb.client, AppDb.db);
await setupDbIndexes();
initRunnerManager();
initCleanJobsTask();
initRepoSyncTask();
initRefreshAuthTokensTask();
const app = express();
app.use(morgan('tiny'));
app.use(json({
verify: (req: any, res, buf) => {
// store raw body for signature verification
if (
Buffer.isBuffer(buf)
&& (
// https://developer.github.com/webhooks/event-payloads/#delivery-headers
req.header(GITHUB_WEBHOOK_SIGNATURE_HEADER)
// https://docs.gitea.io/en-us/webhooks/#example
|| req.header(GITEA_WEBHOOK_SIGNATURE_HEADER)
)
) {
// import cloneBuffer from 'clone-buffer';
// req.rawBody = cloneBuffer(buf);
req.rawBody = buf;
}
return true;
},
}));
app.use(cookieParser());
app.use(cors({
origin: env.METROLINE_UI_URL,
credentials: true,
}));
app.use(passport.initialize());
app.use(authorizeReq);
app.use(routes);
app.use(handleError);
const server = env.METROLINE_SSL_KEY && env.METROLINE_SSL_CERT
? createSecureServer({
key: await promises.readFile(env.METROLINE_SSL_KEY),
cert: await promises.readFile(env.METROLINE_SSL_CERT),
}, app)
: createServer(app);
server.listen(env.METROLINE_PORT, () => {
logger.info(`Listening on port ${chalk.bold.green(env.METROLINE_PORT)}`);
});
io.listen(server);
}
Example #19
Source File: http-server.ts From sdkgen with MIT License | 5 votes |
constructor(public apiConfig: BaseApiConfig<ExtraContextT>, ...maybeExtraContext: {} extends ExtraContextT ? [{}?] : [ExtraContextT]) {
this.extraContext = (maybeExtraContext[0] ?? {}) as ExtraContextT;
this.httpServer = createServer(this.handleRequest.bind(this));
this.enableCors();
this.attachRestHandlers();
const targetTable = [
["/targets/android/client.kt", (ast: AstRoot) => generateAndroidClientSource(ast, true)],
["/targets/android/client_without_callbacks.kt", (ast: AstRoot) => generateAndroidClientSource(ast, false)],
["/targets/dotnet/api.cs", generateCSharpServerSource],
["/targets/dotnet/api.fs", generateFSharpServerSource],
["/targets/flutter/client.dart", generateDartClientSource],
["/targets/ios/client.swift", (ast: AstRoot) => generateSwiftClientSource(ast, false)],
["/targets/ios/client-rx.swift", (ast: AstRoot) => generateSwiftClientSource(ast, true)],
["/targets/node/api.ts", generateNodeServerSource],
["/targets/node/client.ts", generateNodeClientSource],
["/targets/web/client.ts", generateBrowserClientSource],
] as const;
for (const [path, generateFn] of targetTable) {
this.addHttpHandler("GET", path, (_req, res) => {
if (!this.introspection) {
res.statusCode = 404;
res.end();
return;
}
try {
res.setHeader("Content-Type", "application/octet-stream");
res.write(generateFn(this.apiConfig.ast));
} catch (e) {
console.error(e);
res.statusCode = 500;
res.write(`${e}`);
}
res.end();
});
}
this.addHttpHandler("GET", "/ast.json", (_req, res) => {
if (!this.introspection) {
res.statusCode = 404;
res.end();
return;
}
res.setHeader("Content-Type", "application/json");
res.write(JSON.stringify(apiConfig.astJson));
res.end();
});
this.addHttpHandler("GET", /^\/playground.*/u, (req, res) => {
if (!this.introspection) {
res.statusCode = 404;
res.end();
return;
}
if (req.url) {
req.url = req.url.endsWith("/playground") ? req.url.replace(/\/playground/u, "/index.html") : req.url.replace(/\/playground/u, "");
}
staticFilesHandler(req, res, {
cleanUrls: false,
directoryListing: false,
etag: true,
public: PLAYGROUND_PUBLIC_PATH,
}).catch(e => {
console.error(e);
res.statusCode = 500;
res.write(`${e}`);
res.end();
});
});
}
Example #20
Source File: index.ts From stellar-anchor-tests with Apache License 2.0 | 5 votes |
httpServer = createServer(app)
Example #21
Source File: index.ts From CloudProxy with MIT License | 5 votes |
createServer((req: IncomingMessage, res: ServerResponse) => {
// count the request for the log prefix
log.incRequests()
const startTimestamp = Date.now()
log.info(`Incoming request: ${req.method} ${req.url}`)
const bodyParts: any[] = []
req.on('data', chunk => {
bodyParts.push(chunk)
}).on('end', () => {
// parse params
const body = Buffer.concat(bodyParts).toString()
let params: BaseAPICall = null
try {
params = JSON.parse(body)
} catch (err) {
errorResponse('Body must be in JSON format', res, startTimestamp)
return
}
const ctx: RequestContext = {
req,
res,
startTimestamp,
errorResponse: (msg) => errorResponse(msg, res, startTimestamp),
successResponse: (msg, extendedProperties) => successResponse(msg, extendedProperties, res, startTimestamp)
}
// validate params
if (!validateIncomingRequest(ctx, params)) { return }
// process request
Router(ctx, params).catch(e => {
console.error(e)
ctx.errorResponse(e.message)
})
})
}).listen(serverPort, serverHost, () => {
log.info(`CloudProxy v${version} listening on http://${serverHost}:${serverPort}`)
})
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 |
constructor(private port = 1337) {
this.server = createServer(this.router.bind(this));
this.base = `http://localhost:${this.port}`;
}
Example #24
Source File: server.ts From discord-statuspage-v2 with MIT License | 5 votes |
createServer(async (req: IncomingMessage, res: ServerResponse) => {
const { pathname, searchParams } = new URL(req.url, oauth.base)
if (searchParams.get('code')) {
const accessCode: string | string[] = searchParams.get('code')
const data: FormData = new FormData()
data.append('client_id', oauth.CLIENT_ID)
data.append('client_secret', oauth.CLIENT_SECRET)
data.append('grant_type', 'authorization_code')
data.append('redirect_uri', oauth.REDIRECT)
data.append('scopes', oauth.SCOPES)
data.append('code', accessCode)
const { webhook }: IncomingWebhook = await fetch('https://discordapp.com/api/oauth2/token', {
method: 'POST',
body: data
})
.then(async (res) => await res.json())
.catch((err: Error) => {
router.checkRoute('/error', req, res)
console.error(err)
})
if (!webhook) {
router.checkRoute('/error', req, res)
return
}
await db.addWebhook({
_id: new ObjectId(),
guild_id: webhook.guild_id,
channel_id: webhook.channel_id,
token: webhook.token,
id: webhook.id
})
const initMsg = JSON.stringify({
embeds: [{
description: 'Subscribed to [Discord Status](https://status.discord.com/) updates!',
color: 4437377,
author: {
name: 'Discord Status',
icon_url: 'https://discord.com/assets/2c21aeda16de354ba5334551a883b481.png',
url: ops?.supportServer ?? 'https://status.discordapp.com'
},
footer: {
text: 'To unsubscribe, delete this webhook in Server Settings > Integrations > Webhooks > Discord Status'
}
}]
})
await setupSuccess(initMsg, { webhook })
}
if (searchParams.get('error')) router.checkRoute('/error', req, res)
else router.checkRoute(pathname, req, res)
}).listen(3000)
Example #25
Source File: server.ts From anthem with Apache License 2.0 | 5 votes |
httpServer = createServer(app)
Example #26
Source File: index.ts From big-web-quiz with Apache License 2.0 | 5 votes |
server = createServer(app)
Example #27
Source File: oauthClientServer.spec.ts From cli with Apache License 2.0 | 5 votes |
mockedCreateServer = jest.mocked(
createServer
) as unknown as createServerInitialOverload
Example #28
Source File: server.ts From Full-Stack-React-TypeScript-and-Node with MIT License | 5 votes |
httpServer = createServer(app)
Example #29
Source File: index.ts From Full-Stack-React-TypeScript-and-Node with MIT License | 5 votes |
server = createServer(app)