Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'on-finished' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
server.all(route, graphqlHTTP(async (req, res) => {
// Acquire a new client for every request.
const client = await pg.connectAsync(pgConfig)
try {
// Start a transaction for our client and set it up.
await client.queryAsync('begin')
// If we have a secret, let’s setup the request transaction.
await setupRequestTransaction(req, client, secret, anonymousRole)
// Make sure we release our client back to the pool once the response has
// finished.
onFinished(res, () => {
// Try to end our session with a commit. If it succeeds, release the
// client back into the pool. If it fails, release the client back into
// the pool, but also report that it failed. We cannot report an error in
// the request at this point because it has finished.
client.queryAsync('commit')
.then(() => client.end())
.catch(error => {
console.error(error.stack) // eslint-disable-line no-console
client.end()
})
})
return {
// Await the `graphqlSchema` because it may be a promise.
schema: await graphqlSchema,
context: { client },
constructor(
public readonly request: Request,
public readonly response: Response,
parent: Context,
public readonly serverConfig: RestServerResolvedConfig,
name?: string,
) {
super(parent, name);
this._setupBindings(request, response);
onFinished(this.response, () => {
// Close the request context when the http response is finished so that
// it can be recycled by GC
this.close();
});
}
export const accessLogger: RequestHandler = (req, res, next) => {
const startTime = now();
onFinished(res, () => {
// Compute the end time.
const responseTime = Math.round(now() - startTime);
// Get some extra goodies from the request.
const userAgent = req.get("User-Agent");
// Grab the logger.
const log = req.coral ? req.coral.logger : logger;
// Log this out.
log.debug(
{
url: req.originalUrl || req.url,
method: req.method,
statusCode: res.statusCode,
host: req.hostname,
return (amount, currency=defCurrency) => pwrap(async (req, res, next) => {
const invid = req.get('X-Token') && parseToken(req)
, inv = invid && await charge.fetch(invid)
, paid = inv && inv.status === 'paid' && inv.paid_at > now() - accessExp
if (paid) {
if (!await markSpent(inv)) return res.status(410).send('Error: payment token already spent')
onFinished(res, async _ => await markDone(inv, res))
req.invoice = inv
next()
} else {
const inv = await charge.invoice({
amount, currency
, metadata: { source: 'paypercall', req: only(req, 'method', 'path') }
, description: `Pay to call ${req.method} ${req.path}`
, expiry: invoiceExp
})
res.status(402) // Payment Required
.type('application/vnd.lightning.bolt11')
.set('X-Token', makeToken(req, inv.id))
.send(inv.payreq)
}
})
return (req, res, next) => {
const startTime = now();
onFinished(res, () => {
// Compute the end time.
const responseTime = Math.round(now() - startTime);
// Increment the request counter.
httpRequestsTotal.labels(`${res.statusCode}`, req.method).inc();
// Only compute the request path when status code isn't 404 to avoid flood
if (res.statusCode !== 404) {
// Add the request duration.
httpRequestDurationMilliseconds
.labels(req.method, req.baseUrl + req.path)
.observe(responseTime);
}
});
next();
};
function serve(stat) {
if (onFinished.isFinished(res)) {
return;
}
// Do a MIME lookup, fall back to octet-stream and handle gzip
// and brotli special case.
const defaultType = opts.contentType || 'application/octet-stream';
let contentType = mime.getType(file, defaultType);
let charSet;
const range = (req.headers && req.headers.range);
const lastModified = (new Date(stat.mtime)).toUTCString();
const etag = generateEtag(stat, weakEtags);
let cacheControl = cache;
if (contentType) {
charSet = mime.lookupCharset(contentType);
if (charSet) {
N.wire.after(CHANNELS, { priority: 100 }, function response_send(env) {
var res = env.origin.res,
headers = env.headers,
body = env.body,
statusCode;
// If someone already sent reply - do nothing
if (isFinished(res)) return;
// That should not happen, because custom senders should wait
// stream end.
if (res.headerSent) return;
//
// Set some obligatory headers
//
headers.Server = headers.Server || 'Sansun Calakci';
// added by node automatically
// headers['Date'] = headers['Date'] || new Date).toUTCString();
//
// Remove Accept-Ranges if it wasn't explicitly set
//
N.wire.after(CHANNELS, { priority: 100 }, function response_send(env) {
var res = env.origin.res,
headers = env.headers,
body = env.body,
statusCode;
// If someone already sent reply - do nothing
if (isFinished(res)) return;
// That should not happen, because custom senders should wait
// stream end.
if (res.headerSent) return;
//
// Set some obligatory headers
//
headers.Server = headers.Server || 'Sansun Calakci';
// added by node automatically
// headers['Date'] = headers['Date'] || new Date).toUTCString();
//
// Remove Accept-Ranges if it wasn't explicitly set
//
function serve(stat) {
if (onFinished.isFinished(res)) {
return;
}
// Do a MIME lookup, fall back to octet-stream and handle gzip
// and brotli special case.
const defaultType = opts.contentType || 'application/octet-stream';
let contentType = mime.getType(file, defaultType);
let charSet;
const range = (req.headers && req.headers.range);
const lastModified = (new Date(stat.mtime)).toUTCString();
const etag = generateEtag(stat, weakEtags);
let cacheControl = cache;
if (contentType) {
charSet = mime.lookupCharset(contentType);
if (charSet) {
concat({ encoding: 'buffer' }, function(body) {
onFinished(req, function() {
cb(null, res, body)
})
}),
)