How to use the firebase-functions.runWith function in firebase-functions

To help you get started, we’ve selected a few firebase-functions examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github celo-org / celo-monorepo / packages / faucet / src / index.ts View on Github external
import * as admin from 'firebase-admin'
import * as functions from 'firebase-functions'
import { getNetworkConfig } from './config'
import { AccountPool, processRequest } from './database-helper'

const PROCESSOR_RUNTIME_OPTS: functions.RuntimeOptions = {
  // When changing this, check that actionTimeoutMS is less than this number
  timeoutSeconds: 120,
}
admin.initializeApp(functions.config().firebase)

const db = admin.database()

const SECOND = 1000

export const faucetRequestProcessor = functions
  .runWith(PROCESSOR_RUNTIME_OPTS)
  .database.ref('/{network}/requests/{request}')
  .onCreate(async (snap, ctx) => {
    const network: string = ctx.params.network
    const config = getNetworkConfig(network)
    const pool = new AccountPool(db, network, {
      retryWaitMS: SECOND,
      getAccountTimeoutMS: 20 * SECOND,
      actionTimeoutMS: 90 * SECOND,
    })
    return processRequest(snap, pool, config)
  })

// From https://firebase.googleblog.com/2019/04/schedule-cloud-functions-firebase-cron.html
// export const scheduledFunctionCrontab = functions.pubsub.schedule('5 11 * * *').onRun((context) => {
//   console.log('This will be run every day at 11:05 AM UTC!')
github ebidel / puppeteer-functions / functions / index.js View on Github external
res.type('image/png').send(buffer);
  } catch (e) {
    res.status(500).send(e.toString());
  }

  await browser.close();
});

app.get('/version', async function versionHandler(req, res) {
  const browser = res.locals.browser;
  res.status(200).send(await browser.version());
  await browser.close();
});

const beefyOpts = {memory: '2GB', timeoutSeconds: 60};
exports.screenshot = functions.runWith(beefyOpts).https.onRequest(app);
exports.render = functions.runWith(beefyOpts).https.onRequest(app);
exports.version = functions.https.onRequest(app);
exports.test = functions.https.onRequest(app);

// exports.test = functions.https.onRequest(async (req, res) => {
//   const {exec} = require('child_process');
//   const os = require('os');

//   exec('uname -a', (error, stdout, stderr) => {
//     if (error) {
//       console.error(`exec error: ${error}`);
//     }
//     const str = stdout;
//     res.status(200).send(str + '\n' + `${process.platform}, ${String(os.release())}, ${os.arch()}`);
//   });
github bpetetot / conference-hall / functions / api / index.js View on Github external
const runtimeOpts = {
  timeoutSeconds: 300,
  memory: '1GB',
}

// configure express server
const app = express()

// API router v1
app.use('/api/v1', routerV1)

// API privates and authenticated
app.use('/api/private', routerPrivate)

module.exports = functions.runWith(runtimeOpts).https.onRequest(app)
github firebase / oss-bot / functions / src / metrics.ts View on Github external
.runWith(util.FUNCTION_OPTS)
  .https.onRequest(async (req, res) => {
    // TODO: Create project inline
    const projectId = req.param("project");

    try {
      for (let i = 1; i <= 30; i++) {
        await storeDailyMetrics(projectId, admin.database(), i);
      }
      res.status(200).send(`${projectId} --> done`);
    } catch (e) {
      res.status(500).send(`Failed to store ${projectId}: ${e}`);
    }
  });

export const UpdateMetricsWebhook = functions
  .runWith(util.FUNCTION_OPTS)
  .https.onRequest(async (req, res) => {
    const projectId = req.param("project");
    try {
      await storeDailyMetrics(projectId, admin.database());
      res.status(200).send("Done.");
    } catch (e) {
      res.status(500).send("Failed: " + e);
    }
  });

export const UpdateMetrics = functions
  .runWith(util.FUNCTION_OPTS)
  .pubsub.topic("update-metrics")
  .onPublish(async (message, context) => {
    const projectId = message.json["project"];
github ffxiv-teamcraft / ffxiv-teamcraft / functions / index.js View on Github external
};

// Firestore counts
exports.firestoreCountlistsCreate = functions.runWith(runtimeOpts).firestore.document('/lists/{uid}').onCreate(() => {
  const ref = admin.database().ref('/list_count');
  const creationsRef = admin.database().ref('/lists_created');
  // Increment the number of lists created using the tool.
  creationsRef.transaction(current => {
    return current + 1;
  }).then(() => null);
  return ref.transaction(current => {
    return current + 1;
  }).then(() => null);
});

exports.firestoreCountlistsDelete = functions.runWith(runtimeOpts).firestore.document('/lists/{uid}').onDelete(() => {
  const ref = admin.database().ref('/list_count');
  return ref.transaction(current => {
    return current - 1;
  }).then(() => null);
});

validatedCache = {};

exports.userIdValidator = functions.runWith(runtimeOpts).https.onRequest((request, response) => {
  const userId = request.query.userId;
  if (validatedCache[userId] !== undefined) {
    return response.status(200).set('Content-Type', 'application/json').send(`{"valid": ${validatedCache[userId]}}`);
  }
  return firestore.collection('users').doc(userId).get().then(snap => {
    validatedCache[userId] = snap.exists;
    response.status(200).set('Content-Type', 'application/json').send(`{"valid": ${snap.exists}}`);
github firebase / firebase-functions / integration_test / functions / src / storage-tests.ts View on Github external
import * as functions from 'firebase-functions';
import { expectEq, TestSuite } from './testing';
import ObjectMetadata = functions.storage.ObjectMetadata;

export const storageTests: any = functions
  .runWith({
    timeoutSeconds: 540,
  })
  .storage.bucket()
  .object()
  .onFinalize((s, c) => {
    const testId = s.name.split('.')[0];
    return new TestSuite('storage object finalize')

      .it('should not have event.app', (data, context) => !(context as any).app)

      .it('should have the right eventType', (snap, context) =>
        expectEq(context.eventType, 'google.storage.object.finalize')
      )

      .it('should have eventId', (snap, context) => context.eventId)
github swiftwasm / swiftwasm-compile-service / FirebaseFunction / functions / index.js View on Github external
const functions = require("firebase-functions");
const service = require("./service");

service.needsLibraryPath = true;

exports.compile = functions
	.runWith({memory: '2GB'})
	.https.onRequest(service.app);
github jsmonday / Cezanne / functions / index.js View on Github external
id: data.id, 
        data: {
          og_image_url: ogUrl,
          ig_image_url: igUrl
      }})
    }

    resolve({ 
      opengraph: ogUrl,
      instagram: igUrl
    });

  });
}

exports.cezanne = functions
  .runWith({ memory: '1GB', timeoutSeconds: 120 })
  .https
  .onRequest(async (req, res) => {

    const q      = req.body;
    const target = q.target;

    const { opengraph, instagram } = await getImages(q, target);

    res.json({ opengraph, instagram });
  });
github ffxiv-teamcraft / ffxiv-teamcraft / functions / index.js View on Github external
}).then(() => null);
  return ref.transaction(current => {
    return current + 1;
  }).then(() => null);
});

exports.firestoreCountlistsDelete = functions.runWith(runtimeOpts).firestore.document('/lists/{uid}').onDelete(() => {
  const ref = admin.database().ref('/list_count');
  return ref.transaction(current => {
    return current - 1;
  }).then(() => null);
});

validatedCache = {};

exports.userIdValidator = functions.runWith(runtimeOpts).https.onRequest((request, response) => {
  const userId = request.query.userId;
  if (validatedCache[userId] !== undefined) {
    return response.status(200).set('Content-Type', 'application/json').send(`{"valid": ${validatedCache[userId]}}`);
  }
  return firestore.collection('users').doc(userId).get().then(snap => {
    validatedCache[userId] = snap.exists;
    response.status(200).set('Content-Type', 'application/json').send(`{"valid": ${snap.exists}}`);
  });
});

exports.solver = functions.runWith(runtimeOpts).https.onRequest((req, res) => {
  res.set('Access-Control-Allow-Methods', 'POST');
  res.set('Access-Control-Allow-Origin', '*');
  res.set('Access-Control-Allow-Headers', '*');
  res.set('Access-Control-Max-Age', '3600');
  if (req.method === 'OPTIONS') {