diff --git a/functions/package.json b/functions/package.json index bb9a37d0..b48bd764 100644 --- a/functions/package.json +++ b/functions/package.json @@ -13,6 +13,7 @@ }, "main": "lib/index.js", "dependencies": { + "fetch": "1.1.0", "firebase-admin": "10.0.0", "firebase-functions": "3.16.0", "lodash": "4.17.21" diff --git a/functions/src/call-cloud-function.ts b/functions/src/call-cloud-function.ts new file mode 100644 index 00000000..f1e48aa7 --- /dev/null +++ b/functions/src/call-cloud-function.ts @@ -0,0 +1,17 @@ +import * as admin from 'firebase-admin' + +import fetch from './fetch' + +export const callCloudFunction = (functionName: string, data: {} = {}) => { + const projectId = admin.instanceId().app.options.projectId + + let url = `https://us-central1-${projectId}.cloudfunctions.net/${functionName}` + + return fetch(url, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ data }), + }).then((response) => response.json()) +} diff --git a/functions/src/fetch.ts b/functions/src/fetch.ts new file mode 100644 index 00000000..1b54dc6c --- /dev/null +++ b/functions/src/fetch.ts @@ -0,0 +1,9 @@ +let fetchRequest: typeof fetch + +try { + fetchRequest = fetch +} catch { + fetchRequest = require('node-fetch') +} + +export default fetchRequest diff --git a/functions/src/index.ts b/functions/src/index.ts index cde0b30c..5f6cfc99 100644 --- a/functions/src/index.ts +++ b/functions/src/index.ts @@ -2,5 +2,6 @@ import * as admin from 'firebase-admin' admin.initializeApp() +export * from './keep-awake' export * from './place-bet' -export * from './resolve-market' \ No newline at end of file +export * from './resolve-market' diff --git a/functions/src/keep-awake.ts b/functions/src/keep-awake.ts new file mode 100644 index 00000000..cdc701e0 --- /dev/null +++ b/functions/src/keep-awake.ts @@ -0,0 +1,12 @@ +import * as functions from 'firebase-functions' + +import { callCloudFunction } from './call-cloud-function' + +export const keepAwake = functions.pubsub + .schedule('every 1 minutes') + .onRun(async () => { + await Promise.all([ + callCloudFunction('placeBet'), + callCloudFunction('resolveMarket'), + ]) + })