本文整理汇总了TypeScript中firebase-functions.https.onRequest方法的典型用法代码示例。如果您正苦于以下问题:TypeScript https.onRequest方法的具体用法?TypeScript https.onRequest怎么用?TypeScript https.onRequest使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类firebase-functions.https
的用法示例。
在下文中一共展示了https.onRequest方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: ingredientList
import * as functions from 'firebase-functions';
import { DialogflowApp } from 'actions-on-google';
// // Start writing Firebase Functions
// // https://firebase.google.com/docs/functions/typescript
//
export const helloWorld = functions.https.onRequest((request, response) => {
console.log('Request headers: ' + JSON.stringify(request.headers));
console.log('Request body: ' + JSON.stringify(request.body));
let dialogApp = new DialogflowApp({ request, response });
function ingredientList(app: DialogflowApp) {
app.tell(`I see you want to know about ${app.getArgument('recipe_name')}`);
}
let actionMap = new Map();
actionMap.set('IngredientList', ingredientList);
dialogApp.handleRequest(actionMap);
});
示例2: addEvent
});
});
}
exports.addEventToCalendar = functions.https.onRequest((request, response) => {
const eventData = {
eventName: request.body.eventName,
description: request.body.description,
startTime: request.body.startTime,
endTime: request.body.endTime
};
const oAuth2Client = new OAuth2(
googleCredentials.web.client_id,
googleCredentials.web.client_secret,
googleCredentials.web.redirect_uris[0]
);
oAuth2Client.setCredentials({
refresh_token: googleCredentials.refresh_token
});
addEvent(eventData, oAuth2Client).then(data => {
response.status(200).send(data);
return;
}).catch(err => {
console.error('Error adding event: ' + err.message);
response.status(500).send(ERROR_RESPONSE);
return;
});
});
示例3: require
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require('./app/main');
const engine = ngExpressEngine({
bootstrap: AppServerModuleNgFactory,
providers: [
provideModuleMap(LAZY_MODULE_MAP)
]
});
const document: string = fs.readFileSync(__dirname + '/app/index.html', 'utf8').toString();
const app = express();
app.get('**', (req, res) => {
const url: string = req.path;
engine(url, {
req,
res,
url,
document,
bootstrap: AppServerModuleNgFactory,
providers: [
provideModuleMap(LAZY_MODULE_MAP)
]
}, (err?: Error, html: string = 'oops') => {
res.set('Cache-Control', 'public, max-age=3600, s-maxage=43200');
res.send((err) ? err.message : html);
});
});
export const ssr = functions.https.onRequest(app);
示例4: getUsersDQ
import * as functions from 'firebase-functions';
import * as admin from "firebase-admin";
import { getUsersDQ } from "../getUsers";
import { getDaysCurrent } from "../util/getDaysCurrent";
import { getPeriodicityQuestion } from "./getPeriodicityQuestion";
export const activeQuestions = functions.https.onRequest((req, response) => {
let isFlag = false;
getUsersDQ().then((DQs:Array<any>) => {
if(isFlag)
return
isFlag = true;
for (const dq of DQs) {
if (!dq)
return;
if(dq.answers) {
for (let i = 0; i < dq.answers.length; i++)
if(getDaysCurrent(dq,i) >= getPeriodicityQuestion(dq,i))
admin.database().ref(`/${dq['uidCT']}/users/${dq['id']}/questions/${i}`).update({isActive: true})
}
}
response.send("Questoes ativadas!");
}).catch(() => console.log('Error para ativar as questĂľes'));
});
示例5: setGithubStatus
export const payloadGithubStatus = https.onRequest(async (request, response) => {
const authToken = request.header('auth-token');
const commitSha = request.header('commit-sha');
const packageName = request.header('package-name');
const packageSize = parseFloat(request.header('package-full-size'));
const packageDiff = parseFloat(request.header('package-size-diff'));
if (!verifyToken(authToken)) {
return response.status(403).json({message: 'Auth token is not valid'});
}
if (!commitSha) {
return response.status(404).json({message: 'No commit has been specified'});
}
if (isNaN(packageDiff)) {
return response.status(400).json({message: 'No valid package difference has been specified.'});
}
if (isNaN(packageSize)) {
return response.status(400).json({message: 'No full size of the package has been specified.'});
}
if (!packageName) {
return response.status(400).json({message: 'No package name has been specified.'});
}
if (packageDiff === 0) {
return response.status(400).json({message: `The difference equals zero. Status won't be set.`});
}
// Better message about the diff that shows whether the payload increased or decreased.
const diffMessage = packageDiff < 0 ? 'decrease' : 'increase';
const diffFormatted = Math.abs(packageDiff).toFixed(2);
await setGithubStatus(commitSha, {
result: true,
name: `${capitalizeFirstLetter(packageName)} Payload Size`,
description: `${packageSize}kb / ${diffFormatted}kb ${diffMessage} (ES2015 bundle)`
});
response.json({message: 'Payload Github status successfully set.'});
});
示例6: cors
export const linkedin = functions.https.onRequest((req, res) => {
cors(req, res, () => {
admin.database().ref('linkedin').once('value', (snapshot: admin.database.DataSnapshot) => {
if (snapshot.exists() && snapshot.val().expires > new Date().getTime()) {
return res.status(400).send('Functions only update data that\'s older than 24 hours.');
} else {
const tomorrow: number = new Date().getTime() + 86400000;
admin.storage().bucket().file('linkedin.html', {})
.getSignedUrl({ action: 'read', expires: tomorrow })
.then((url: string[]) => {
if (url.length !== 1) return res.status(400).send('No profile found');
httpRequest({ method: 'GET', url: url[0] }, (error: any, response: any, body: string) => {
if (error) { return res.status(error.code).send(error.message); }
inScrape.getProfile(body)
.then((profile) => {
const regex: RegExp = RegExp('<img.*?alt="' + profile.name + '".*?src=".\/linkedin_files\/(.*?)"', 'g');
const images: string[] = regex.exec(body);
if (Array.isArray(images) && images.length > 0) { profile.photo = 'https://media.licdn.com/mpr/mpr/' + images[1]; }
if (profile.experience && Array.isArray(profile.experience)) { profile.experience = orderExperience(profile.experience); }
const result = {
results: profile,
expires: tomorrow
};
admin.database().ref('linkedin').set(result).then(() => res.send(JSON.stringify(result.results)));
}).catch(err => res.status(400).send(err));
});
})
.catch(error => res.status(400).send(error));
}
});
});
});
示例7: require
import * as functions from 'firebase-functions';
const next = require('next');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev, conf: { distDir: 'next' } });
const handle = app.getRequestHandler();
export const nextApp = functions.https.onRequest((req, res) => {
console.log('File: ' + req.originalUrl);
return app.prepare().then(() => handle(req, res));
});
示例8: pub
export const questionBotHandler = functions.https.onRequest(
async (req, res) => {
const body = req.body;
// Slash Command
if (body.command === '/ask') {
await pub(body);
res
.status(200)
.json({ text: BOT_RESPONSE, attachments: { text: BOT_RESPONSE } });
return;
}
// Bot Question
const { type, subtype } = body.event;
const { thread_ts, text } = body.event.message || body.event;
// Attempt to filter invalid questions
const okType = type === 'message';
const okUrl =
thread_ts ||
(text && text.includes('fireship.io')) ||
subtype === 'message_deleted';
// If OK, publish data
if (okType && okUrl) {
await pub(body);
res.sendStatus(200);
}
}
);
示例9: getOpenPullRequestsWithMergeableState
import {https} from 'firebase-functions';
import {getOpenPullRequestsWithMergeableState} from './github/github-graphql-queries';
/**
* Firebase HTTP trigger that responds with a list of Pull Requests that have merge conflicts.
*/
export const pullRequestsWithConflicts = https.onRequest(async (_request, response) => {
const pullRequests = (await getOpenPullRequestsWithMergeableState())
.filter(pullRequest => pullRequest.mergeable === 'CONFLICTING');
response.status(200).json(pullRequests);
});
示例10: corsOptions
import * as functions from 'firebase-functions'
import * as admin from 'firebase-admin';
import * as corsOptions from 'cors';
import serviceAccount from "./etc/service-key";
import { Forum } from './model/forum/forum';
const cors = corsOptions({ origin: true });
const app = admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://" + serviceAccount.project_id + ".firebaseio.com"
});
const db = app.database();
exports.postApi = functions.https.onRequest((req, res) => {
cors(req, res, () => {
console.log("postApi() begins!");
let forum = new Forum(db.ref('/'));
//res.send( JSON.stringify( req.body ) + JSON.stringify( req.params ) + JSON.stringify( req.query ) );
forum.postApi(req.body)
.then(x => res.send({code: 0, data: x}))
.catch(e => res.send({ code: e.message, message: forum.getLastErrorMessage }));
console.log("Send");
});
});