@vercel/node#NowRequest TypeScript Examples
The following examples show how to use
@vercel/node#NowRequest.
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 telechan with MIT License | 6 votes |
// main function
export default async function handle(req: NowRequest, res: NowResponse) {
try {
await useWebhook(req, res);
} catch (e) {
res.statusCode = 500;
res.json(e.message);
}
}
Example #2
Source File: [num].ts From natemoo-re with MIT License | 6 votes |
export default async function (req: NowRequest, res: NowResponse) {
const { query: { num }, headers } = req;
const index = Number.parseInt(num as string) - 1;
const dest = headers["sec-fetch-dest"] || headers["Sec-Fetch-Dest"];
const accept = headers['accept'];
const image = dest ? dest === 'image' : !/text\/html/.test(accept);
const color = await getBlockColor(index);
if (image) {
const svg = renderToString(Block({ color }));
const etag = createHash("md5").update(svg).digest("hex");
res.setHeader("Content-Type", "image/svg+xml");
res.setHeader("Cache-Control", "no-cache, max-age=0");
res.setHeader("Etag", etag);
return res.status(200).send(svg);
}
const newColor: string = getNextColor(color);
await setBlockColor(index, newColor);
return res.status(204).end();
}
Example #3
Source File: now-playing.ts From natemoo-re with MIT License | 6 votes |
export default async function (req: NowRequest, res: NowResponse) {
const {
item = ({} as any),
is_playing: isPlaying = false,
progress_ms: progress = 0,
} = await nowPlaying();
const params = decode(req.url.split("?")[1]) as any;
if (params && typeof params.open !== "undefined") {
if (item && item.external_urls) {
res.writeHead(302, {
Location: item.external_urls.spotify,
});
return res.end();
}
return res.status(200).end();
}
res.setHeader("Content-Type", "image/svg+xml");
res.setHeader("Cache-Control", "s-maxage=1, stale-while-revalidate");
const { duration_ms: duration, name: track } = item;
const { images = [] } = item.album || {};
const cover = images[images.length - 1]?.url;
let coverImg = null;
if (cover) {
const buff = await (await fetch(cover)).arrayBuffer();
coverImg = `data:image/jpeg;base64,${Buffer.from(buff).toString("base64")}`;
}
const artist = (item.artists || []).map(({ name }) => name).join(", ");
const text = renderToString(
Player({ cover: coverImg, artist, track, isPlaying, progress, duration })
);
return res.status(200).send(text);
}
Example #4
Source File: top-tracks.ts From natemoo-re with MIT License | 6 votes |
export default async function (req: NowRequest, res: NowResponse) {
let { i, open } = req.query;
i = Array.isArray(i) ? i[0] : i;
const item = await topTrack({ index: Number.parseInt(i) });
if (!item) {
return res.status(404).end();
}
if (typeof open !== "undefined") {
if (item && item.external_urls) {
res.writeHead(302, {
Location: item.external_urls.spotify,
});
return res.end();
}
return res.status(200).end();
}
res.setHeader("Content-Type", "image/svg+xml");
res.setHeader("Cache-Control", "s-maxage=1, stale-while-revalidate");
const { name: track } = item;
const { images = [] } = item.album || {};
const cover = images[images.length - 1]?.url;
let coverImg = null;
if (cover) {
const buff = await (await fetch(cover)).arrayBuffer();
coverImg = `data:image/jpeg;base64,${Buffer.from(buff).toString("base64")}`;
}
const artist = (item.artists || []).map(({ name }) => name).join(", ");
const text = renderToString(
Track({ index: Number.parseInt(i), cover: coverImg, artist, track })
);
return res.status(200).send(text);
}
Example #5
Source File: telegram.ts From telechan with MIT License | 5 votes |
export async function useWebhook(req: NowRequest, res: NowResponse) {
if( req.url?.substring(0,9) == '/api/send' ){
const text = req.query?.text || req.body?.text || "";
const sendkey = req.query?.sendkey || req.body?.sendkey || "";
const desp = req.query?.desp || req.body?.desp || "";
const markdown = req.query?.markdown || req.body?.markdown || "";
if( text == "" || sendkey == "" )
{
throw new Error('text & sendkey cannot be empty');
}
else
{
const key_info:String[] = String(sendkey).split("T");
if( key_info[1] != md5( TCKEY+key_info[0] ) )
{
throw new Error('sendkey error');
}
else
{
var params = new URLSearchParams();
params.append("chat_id",String(key_info[0]));
let content = String(text)+"\n\n"+String(desp);
if( markdown != "" )
{
content += String(markdown);
params.append("parse_mode","MarkdownV2");
}
params.append("text",content);
const ret = await axios.post( "https://api.telegram.org/bot" + BOT_TOKEN + "/sendMessage" , params );
res.status(200).json( ret.data );
}
}
}
try {
if (!isDev && !VERCEL_URL) {
throw new Error("VERCEL_URL is not set.");
}
const getWebhookInfo = await bot.telegram.getWebhookInfo();
const botInfo = await bot.telegram.getMe();
bot.options.username = botInfo.username;
console.info("Server has initialized bot username using Webhook. ", botInfo.username);
if (getWebhookInfo.url !== VERCEL_URL + "/api") {
debug(`deleting webhook`);
await bot.telegram.deleteWebhook();
debug(`setting webhook to ${VERCEL_URL}/api`);
await bot.telegram.setWebhook(`${VERCEL_URL}/api`);
}
// call bot commands and middlware
botUtils();
// console.log("webhook already defined");
// console.log("request method: ", req.method);
// console.log("req.body", req.body);
if (req.method === "POST") {
await bot.handleUpdate(req.body, res);
} else {
ok(res, "Listening to bot events...");
}
} catch (error) {
console.error(error);
return error.message;
}
}
Example #6
Source File: join-classes-mailing-list.ts From cpinitiative with Mozilla Public License 2.0 | 4 votes |
export default async function joinClassesMailingList(
request: NowRequest,
response: NowResponse
) {
console.log("running")
const { email, tags: unprocessedTags } = request.body
if (!unprocessedTags || !email) {
response.status(400).json({
success: false,
code: "missing_parameters",
message: "Either the email or tags field was not provided.",
})
return
}
const tags = unprocessedTags.split(",")
try {
const listID = "e122c7f3eb"
let emailHash = createHash("md5").update(email.toLowerCase()).digest("hex")
const existingDataResponse = await axios
.get(
`https://us2.api.mailchimp.com/3.0/lists/${listID}/members/${emailHash}`,
{
auth: {
username: "no-username",
password: MAILCHIMP_API_KEY,
},
}
)
.catch(e => {
// console.log("Unable to GET existing mailchimp fields", e)
// the user probably doesn't exist
// so just assume there is no previous data
return Promise.resolve({})
})
const transformedTags = []
if (tags.indexOf("classes") > -1) {
transformedTags.push({
name: "Classes Info",
status: "active",
})
}
if (tags.indexOf("general") > -1) {
transformedTags.push({
name: "General",
status: "active",
})
}
if (tags.indexOf("contests") > -1) {
transformedTags.push({
name: "Contest Info",
status: "active",
})
}
if (
Object.keys(existingDataResponse).length > 0 &&
(existingDataResponse as AxiosResponse).data.tags &&
transformedTags.every(
tag =>
(existingDataResponse as AxiosResponse).data.tags.findIndex(
c => c.name === tag.name
) > -1
)
) {
response.status(409).json({
success: false,
code: "already_subscribed",
message: "The email is already part of the Classes Info list.",
})
return
}
const data = {
email_address: email,
status: "subscribed",
status_if_new: "subscribed",
ip_signup: request.headers["client-ip"],
}
await axios.put(
`https://us2.api.mailchimp.com/3.0/lists/${listID}/members/${emailHash}`,
data,
{
auth: {
username: "no-username",
password: MAILCHIMP_API_KEY,
},
}
)
await axios.post(
`https://us2.api.mailchimp.com/3.0/lists/${listID}/members/${emailHash}/tags`,
{
tags: transformedTags,
},
{
auth: {
username: "no-username",
password: MAILCHIMP_API_KEY,
},
}
)
} catch (error) {
console.log("INTERNAL ERROR", error)
console.log(error.response.data)
response.status(500).json({
success: false,
code: "internal_error",
mailchimpErrorData: { ...error.response.data }, // in case of circular JSON
})
return
}
response.status(200).json({
success: true,
code: "subscribed",
})
}