next#NextApiResponse TypeScript Examples
The following examples show how to use
next#NextApiResponse.
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: notionPageData.ts From pagely with MIT License | 7 votes |
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
try {
const pageId = req.query.pageId;
const notion = new NotionAPI();
const recordMap = await notion.getPage(pageId.toString());
console.log({
success: true,
recordMap: recordMap,
});
res.setHeader('Cache-Control', 's-maxage=2');
res.json({
success: true,
recordMap: recordMap,
});
} catch (e) {
console.log(e);
res.json({
success: false,
});
}
}
Example #2
Source File: subscribe.ts From aljoseph.co with MIT License | 7 votes |
handler = async (req: NextApiRequest, res: NextApiResponse) => {
const { fName, email } = req.body;
if (!email) {
return res.status(400).json({ error: 'Email is required' });
}
try {
await mailchimp.lists.addListMember(process.env.MAILCHIMP_AUDIENCE_ID, {
email_address: email,
status: 'pending',
merge_fields: {
FNAME: fName
}
});
return res.status(201).json({ error: '' });
} catch (error) {
if (error.status >= 400) {
const { text } = error.response;
if (text.includes('Member Exists')) {
return res.status(400).json({
error: `You're already subscribed to my mailing list.`
});
}
}
return res.status(500).json({ error: error.message || error.toString() });
}
}
Example #3
Source File: _utils.ts From ksana.in with Apache License 2.0 | 7 votes |
sendError5xx = (res: NextApiResponse, error: Error): boolean => {
res.statusCode = 500
res.json({
success: false,
data: null,
error: error
})
return false
}
Example #4
Source File: metadata.ts From pawnft with GNU General Public License v3.0 | 6 votes |
metadata = async (req: NextApiRequest, res: NextApiResponse) => {
// Collect required parameters
const { name, description, imageURL, tokenAddress, tokenId } = req.body;
// Enforce required parameters
if (!name || !description || !imageURL || !tokenAddress || !tokenId) {
res.status(502).send({ error: "Missing parameters" });
}
// Setup redis and data structure
const client = new Redis(process.env.REDIS_URL);
let existingData = await client.get("metadata");
let newData: Record<string, Record<string, string>> = {};
// If data exists
if (existingData) {
// Parse and replace structure
newData = JSON.parse(existingData);
}
// Update structure with new metadata
newData[`${tokenAddress.toLowerCase()}-${tokenId.toString()}`] = {
name,
description,
imageURL,
};
// Save metadata and return
await client.set("metadata", JSON.stringify(newData));
res.status(200).send({ success: true });
}
Example #5
Source File: sendEmail.ts From next-saas-starter with MIT License | 6 votes |
export default async function SendEmail(req: NextApiRequest, res: NextApiResponse) {
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const { subject, description, email, name } = req.body;
const referer = req.headers.referer;
const content = {
to: ['[email protected]'],
from: '[email protected]',
subject: subject,
text: description,
html: `<div>
<h1>Name: ${name}</h1>
<h1>E-mail: ${email}</h1>
<p>${description}</p>
<p>Sent from: ${referer || 'Not specified or hidden'}`,
};
try {
await sgMail.send(content);
res.status(204).end();
} catch (error) {
console.log('ERROR', error);
res.status(400).send({ message: error });
}
}
Example #6
Source File: driveHandler.ts From frames with Mozilla Public License 2.0 | 6 votes |
/**
* @desc returns a 206 morsel response of a video based on the range requested
* @param id - id of file tp be requested
* @param dest - destination for stream buffer outbound stream
* @param range - HTTP request range requested
*/
streamFile = async (id: string, dest: NextApiResponse, range: string) => {
const file = await this.getFile(id);
if (file){
let {start, end, chunkSize, fileSize, mimeType} = this.buildRange(range, file);
dest.writeHead(206, {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunkSize,
'Content-Type': mimeType
})
let {data} = await this.drive.files.get({
fileId: id,
alt: 'media',
supportsAllDrives: true,
}, {responseType: 'stream', headers: {Range: `bytes=${start}-${end}`}});
data.pipe(dest);
} else dest.status(404).json('file no longer exists');
}
Example #7
Source File: rate-limit.ts From staticshield with MIT License | 6 votes |
rateLimit = (options) => {
const tokenCache = new LRU({
max: parseInt(options.uniqueTokenPerInterval || 500, 10),
maxAge: parseInt(options.interval || 60000, 10),
});
return {
check: (res: NextApiResponse, limit, token: string) =>
new Promise<void>((resolve, reject) => {
const tokenCount = tokenCache.get(token) || [0];
if (tokenCount[0] === 0) {
tokenCache.set(token, tokenCount);
}
tokenCount[0] += 1;
const currentUsage = tokenCount[0];
const isRateLimited = currentUsage >= parseInt(limit, 10);
res.setHeader('X-RateLimit-Limit', limit);
res.setHeader(
'X-RateLimit-Remaining',
isRateLimited ? 0 : limit - currentUsage
);
return isRateLimited ? reject() : resolve();
}),
};
}
Example #8
Source File: corsMiddleware.ts From excalidraw-json with MIT License | 6 votes |
export function corsMiddleware<
Request extends NextApiRequest = NextApiRequest,
Response = any,
>(
fn: (
req: Request,
res: NextApiResponse<Response>,
) => ReturnType<NextApiHandler>,
): (
req: Request,
res: NextApiResponse<Response>,
) => ReturnType<NextApiHandler> {
return async (req, res) => {
await new Promise<void>((resolve, reject) => {
cors(
// @ts-ignore
req,
res,
(result: Error) => {
if (result) {
return reject(result);
}
resolve();
},
);
});
return fn(req, res);
};
}
Example #9
Source File: analytics.ts From thvu-blog with MIT License | 6 votes |
handlers = async (_: NextApiRequest, res: NextApiResponse<Analytic>) => {
const startDate = "2021-01-01";
const auth = new google.auth.GoogleAuth({
credentials: {
client_email: process.env.GOOGLE_CLIENT_EMAIL,
client_id: process.env.GOOGLE_CLIENT_ID,
private_key: process.env.GOOGLE_PRIVATE_KEY,
},
scopes: ["https://www.googleapis.com/auth/analytics.readonly"],
});
const analytics = google.analytics({
auth,
version: "v3",
});
const response = await analytics.data.ga.get({
"end-date": "today",
ids: "ga:251017969",
metrics: "ga:pageviews",
"start-date": startDate,
});
res.setHeader("Cache-Control", "public, s-maxage=60, stale-while-revalidate=30");
return res.status(200).json({
pageViews: response.data.totalsForAllResults?.["ga:pageviews"],
});
}
Example #10
Source File: main.ts From prox2 with GNU Affero General Public License v3.0 | 6 votes |
function applyMiddleware<T>(
req: NextApiRequest,
res: NextApiResponse,
fn: (arg0: any, arg1: any, cb: (arg0: T) => void) => T
): Promise<T> {
return new Promise((resolve, reject) => {
fn(req, res, (result) => {
if (result instanceof Error) {
return reject(result);
}
return resolve(result);
});
});
}
Example #11
Source File: is-allowed-method.ts From storefront-data-hooks with MIT License | 6 votes |
export default function isAllowedMethod(
req: NextApiRequest,
res: NextApiResponse,
allowedMethods: string[]
) {
const methods = allowedMethods.includes('OPTIONS')
? allowedMethods
: [...allowedMethods, 'OPTIONS']
if (!req.method || !methods.includes(req.method)) {
res.status(405)
res.setHeader('Allow', methods.join(', '))
res.end()
return false
}
if (req.method === 'OPTIONS') {
res.status(200)
res.setHeader('Allow', methods.join(', '))
res.setHeader('Content-Length', '0')
res.end()
return false
}
return true
}
Example #12
Source File: index.ts From website with Apache License 2.0 | 6 votes |
export default function handler(
_req: NextApiRequest,
res: NextApiResponse<APIResponse<IndexResponse>>,
) {
res.status(200).json({
success: true,
data: {
message: "Welcome to dahliaOS' web API!",
},
});
}
Example #13
Source File: top.png.ts From crypto-fees with MIT License | 6 votes |
handler = async (req: NextApiRequest, res: NextApiResponse) => {
const { date } = req.query;
const data = date ? await getHistoricalData(date.toString()) : await getData();
const bundles: { [id: string]: Metadata } = {};
const filteredData = data.filter((val: any) => {
// This is unrelated to filtering, but no need to loop twice
if (val && val.bundle) {
bundles[val.bundle] = getBundle(val.bundle);
}
return !!val;
});
const bundledData = bundleItems(filteredData, bundles);
const svg = ReactDOMServer.renderToString(
React.createElement(SocialCard, {
data: bundledData,
date: date ? date.toString() : formatDate(new Date()),
})
);
const buffer = Buffer.from(svg);
const output = await sharp(buffer, { density: 300 }).toFormat('png').toBuffer();
res.setHeader('Cache-Control', 'max-age=0, s-maxage=240');
res.setHeader('Content-Type', 'image/png');
res.write(output, 'binary');
res.end(null, 'binary');
}
Example #14
Source File: passport.ts From hakka with MIT License | 6 votes |
export async function handleSuccessfulLogin(
req: NextApiRequest,
res: NextApiResponse,
) {
const user = (req as $TsFixMe).user as { id: number }
const authToken = await createSecureToken({
userId: user.id,
})
const maxAge = 60 * 60 * 24 * 90 // 3 month
const authCookie = serialize(AUTH_COOKIE_NAME, authToken, {
path: '/',
httpOnly: true,
sameSite: 'lax',
maxAge,
domain: process.env.NODE_ENV === 'production' ? '.hakka.dev' : undefined,
})
res.setHeader('Set-Cookie', [authCookie])
res.redirect('/')
}
Example #15
Source File: index.ts From reddium with MIT License | 6 votes |
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const { link_id, children, token = "" } = JSON.parse(req.body);
const url = `https://oauth.reddit.com/api/morechildren?api_type=json&link_id=${link_id}&children=${children}`;
const headerOptions = {
headers: { Authorization: `Bearer ${token}` }
};
try {
const resp = await (await fetch(url, headerOptions)).json();
res.status(200).json(resp);
} catch (error) {
res.status(400).json(error);
}
}
Example #16
Source File: index.ts From selftrace with MIT License | 6 votes |
// this file handles requests to /api/libraries
function handler(req: NextApiRequest, res: NextApiResponse) {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
return res.end(
JSON.stringify({
outputData: 47,
})
);
}
Example #17
Source File: auth.ts From ultimate-saas-ts with MIT License | 6 votes |
auth: Middleware<AppNextApiRequest, NextApiResponse> = async (
req,
res,
next
) => {
const session = await getSession({ req });
if (!session) {
return res.status(403).end('Forbidden');
}
req.session = session;
return next();
}
Example #18
Source File: import-events.ts From website with MIT License | 6 votes |
export default async function importEvent(
req: NextApiRequest,
res: NextApiResponse,
): Promise<void> {
if (req.method === 'POST') {
try {
const resultImport = await importDiscordEventsAutomatic();
if (resultImport) {
res.status(200).json({ message: 'Ok' });
} else {
res.status(500).json({ message: 'Automatic migration is disabled' });
}
} catch (error) {
console.log(error);
res.status(500).json({ message: 'Could not import discord events' });
}
} else {
res.status(405).json({ message: 'Method not allowed' });
}
}
Example #19
Source File: index.ts From next-translate-routes with MIT License | 6 votes |
handler = (_req: NextApiRequest, res: NextApiResponse) => {
try {
if (!Array.isArray(sampleUserData)) {
throw new Error('Cannot find user data')
}
res.status(200).json(sampleUserData)
} catch (err) {
res.status(500).json({ statusCode: 500, message: err.message })
}
}
Example #20
Source File: index.ts From core with GNU Affero General Public License v3.0 | 6 votes |
Github = RequestHandler().get(async (_req: NextApiRequest, res: NextApiResponse) => {
res.redirect(
301,
generateOauthURL('github', process.env.GITHUB_CLIENT_ID)
)
})
.delete(async (req: DeleteApiRequest, res) => {
const user = await get.Authorization(req.cookies.token)
if (!user) return ResponseWrapper(res, { code: 401 })
const csrfValidated = checkToken(req, res, req.body._csrf)
if(!csrfValidated) return
await update.Github(user, null)
get.user.clear(user)
return ResponseWrapper(res, { code: 200 })
})
Example #21
Source File: [election_id].ts From electify with MIT License | 6 votes |
handler: unknown = async (req: NextApiRequest, res: NextApiResponse) => {
switch (req.method) {
case 'GET':
{
let { election_id } = req.query as { election_id: string };
if (!election_id) return res.status(400).json({ success: false, error: false });
election_id = election_id.toLowerCase();
const getParams = {
TableName: table,
Key: { election_id },
};
docClient.get(getParams, async (err, data) => {
if (err) return error(err, res);
if (data.Item) {
return res.json({
success: true,
display_name: data.Item.display_name,
candidates: data.Item.candidates,
expiration_time: data.Item.expiration_time,
total_votes: totalVotes(data.Item.candidates),
voters_remaining: data.Item.voters.length,
auth_type: data.Item.auth_type,
} as dataInterface);
}
return res.json({ success: false, error: 'Wrong Election ID' });
});
}
break;
default:
return res.status(405).json({ success: false, error: false });
}
return null;
}
Example #22
Source File: _utils.ts From ksana.in with Apache License 2.0 | 6 votes |
setStatusCode = (res: NextApiResponse, error?: any) => {
if (error) {
res.statusCode = 400
} else {
res.statusCode = 200
}
}
Example #23
Source File: [word].ts From crosshare with GNU Affero General Public License v3.0 | 6 votes |
export default async function clues(req: NextApiRequest, res: NextApiResponse) {
const { word } = req.query;
if (!word || Array.isArray(word)) {
return res.status(404).json({ statusCode: 404, message: 'bad word params' });
}
const clues = await getClues(db, word.toUpperCase());
res.setHeader('X-Robots-Tag', 'noindex');
res.setHeader('Cache-Control', 'public, max-age=172800, s-maxage=172800');
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(clues));
}
Example #24
Source File: email.ts From oxen-website with GNU General Public License v3.0 | 6 votes |
export default async function handler(
req: NextApiRequest,
res: NextApiResponse,
) {
if (req.method !== 'POST') {
res.status(400).json({
message: 'Email API: Invalid http method. | Only POST is accepted.',
});
}
const email = req.body.email;
const response = await fetch(
`https://api.createsend.com/api/v3.2/subscribers/${process.env.CAMPAIGN_MONITOR_LIST_API_ID}.json`,
{
body: JSON.stringify({
EmailAddress: email,
ConsentToTrack: 'Unchanged',
}),
headers: {
'Content-Type': 'application/json',
Authorization: `Basic ${base64.encode(
`${process.env.CAMPAIGN_MONITOR_API_KEY}:x`,
)}`,
},
method: 'POST',
},
);
if (response.status === 201) {
// console.log(`Email API: ${email} subscribed!`);
res.status(201).json({ email });
} else {
// const result = await response.json();
// console.warn(
// `Email API: | Code: ${result.Code} | Email: ${email} | ${result.Message}`
// );
res.status(400).json({ email });
}
}
Example #25
Source File: is-allowed-method.ts From plasmic with MIT License | 6 votes |
export default function isAllowedMethod(
req: NextApiRequest,
res: NextApiResponse,
allowedMethods: HTTP_METHODS[]
) {
const methods = allowedMethods.includes('OPTIONS')
? allowedMethods
: [...allowedMethods, 'OPTIONS']
if (!req.method || !methods.includes(req.method)) {
res.status(405)
res.setHeader('Allow', methods.join(', '))
res.end()
return false
}
if (req.method === 'OPTIONS') {
res.status(200)
res.setHeader('Allow', methods.join(', '))
res.setHeader('Content-Length', '0')
res.end()
return false
}
return true
}
Example #26
Source File: [donationId].tsx From frontend with MIT License | 6 votes |
Handler: NextApiHandler = async (req: NextApiRequest, res: NextApiResponse) => {
const id = Array.isArray(req.query.donationId) ? req.query.donationId[0] : req.query.donationId
const jwt = await getToken({ req })
const { data: donation } = await apiClient.get<UserDonationResponse>(
endpoints.donation.getUserDonation(id).url,
authConfig(jwt?.accessToken),
)
if (!donation) {
res.status(404).json({ notFound: true })
} else {
const pdfStream = await renderToStream(
<Certificate donation={donation} person={donation.person} />,
)
res.setHeader('Content-Type', 'application/pdf')
pdfStream.pipe(res)
}
}
Example #27
Source File: email.tsx From coindrop with GNU General Public License v3.0 | 6 votes |
testHtml: NextApiHandler = async (req: NextApiRequest, res: NextApiResponse) => {
try {
const Body: FC = () => (<div>hiiiii</div>);
const html = generateStaticHTML({
title: "Hello test",
previewText: "Preview text...",
Body,
emailListId: "test-list",
userEmail: '[email protected]',
});
// sesSend({
// to: '[email protected]',
// subject: 'Test e-mail2',
// html,
// });
res.status(200).send(html);
} catch (err) {
console.log(err);
res.status(500).end();
}
}
Example #28
Source File: subscribe.ts From samuelkraft-next with MIT License | 6 votes |
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const { email } = req.body
if (!email) {
return res.status(400).json({ error: 'Email is required' })
}
const result = await fetch('https://www.getrevue.co/api/v2/subscribers', {
method: 'POST',
headers: {
Authorization: `Token ${process.env.REVUE_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ email }),
})
console.log('result', result)
const data = await result.json()
if (!result.ok) {
return res.status(500).json({ error: data.error.email[0] })
}
return res.status(201).json({ error: '' })
}
Example #29
Source File: wrapExpressHandler.ts From solana-pay with Apache License 2.0 | 6 votes |
wrapExpressHandler = function (handler: RequestHandler): NextApiHandler {
return function (request: NextApiRequest, response: NextApiResponse): Promise<void> {
return new Promise<void>(function (resolve, reject) {
handler(request as any, response as any, function (error?: any) {
if (error) {
reject(error);
} else {
resolve();
}
});
});
};
}