next#NextApiRequest TypeScript Examples

The following examples show how to use next#NextApiRequest. 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 vote down vote up
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 vote down vote up
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: metadata.ts    From pawnft with GNU General Public License v3.0 6 votes vote down vote up
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 #4
Source File: sendEmail.ts    From next-saas-starter with MIT License 6 votes vote down vote up
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 #5
Source File: auth.ts    From frames with Mozilla Public License 2.0 6 votes vote down vote up
/**
     * @desc saves the identity of a specific user's session
     * @param sessionId - session id to be stored
     * @param req - request object
     */
    public async saveIdentity(sessionId: string, req: NextApiRequest) {
        const address = requestIp.getClientIp(req);
        const user = await this.getUserFromSession(sessionId);
        const ua = parser(req.headers['user-agent']);
        if (address && address !== '127.0.0.1' && user) {
            const osName = ua.os.name;
            const userId = user.userId;
            const browserName = ua.browser.name + ' ' + ua.browser.version;
            const identity = await this.prisma.userIdentifier.findFirst({where: {address}});
            let country: string, regionName: string, city: string;

            if (identity) {
                city = identity.city;
                country = identity.country;
                regionName = identity.regionName;

            } else {
                const client = await this.makeRequest<IP>('http://ip-api.com/json/' + address, null, 'GET');
                city = client?.city || '';
                country = client?.country || '';
                regionName = client?.regionName || '';
            }

            const data = {osName: osName || '', userId, browserName, sessionId, address, regionName, country, city};
            if (city && country && regionName)
                await this.prisma.userIdentifier.upsert({
                    create: data,
                    update: data,
                    where: {sessionId}
                });
        }
    }
Example #6
Source File: get-site-from-site-id.ts    From staticshield with MIT License 6 votes vote down vote up
async function fetchSitesApi(req: NextApiRequest, res: NextApiResponse) {
  const { user }: { user: UserProfile } = getSession(req, res);
  const data = await fetchSitesFromSiteId(
    user.sub,
    req.query.siteId.toString()
  );

  if (data == [] || undefined || data.length == 0) {
    res.json([]);
    res.end(() => {
      console.log('process ended');
    });
    return;
  }
  res.json(data[0]);
}
Example #7
Source File: corsMiddleware.ts    From excalidraw-json with MIT License 6 votes vote down vote up
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 #8
Source File: analytics.ts    From thvu-blog with MIT License 6 votes vote down vote up
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 #9
Source File: main.ts    From prox2 with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #10
Source File: is-allowed-method.ts    From storefront-data-hooks with MIT License 6 votes vote down vote up
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 #11
Source File: index.ts    From website with Apache License 2.0 6 votes vote down vote up
export default function handler(
  _req: NextApiRequest,
  res: NextApiResponse<APIResponse<IndexResponse>>,
) {
  res.status(200).json({
    success: true,
    data: {
      message: "Welcome to dahliaOS' web API!",
    },
  });
}
Example #12
Source File: top.png.ts    From crypto-fees with MIT License 6 votes vote down vote up
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 #13
Source File: auth.ts    From hakka with MIT License 6 votes vote down vote up
getServerSession = async (
  req: NextApiRequest | IncomingMessage,
): Promise<{ user: AuthUser | null }> => {
  const token = cookie.parse(req.headers.cookie || '')[AUTH_COOKIE_NAME]

  const cookieUserPayload = await parseSecureToken(token)

  if (!cookieUserPayload) {
    return { user: null }
  }

  const user = await prisma.user.findUnique({
    where: {
      id: cookieUserPayload.userId,
    },
  })

  return {
    user: user
      ? {
          id: user.id,
          username: user.username,
          avatar: user.avatar,
          isAdmin: isAdmin({ id: user.id }),
          createdAt: user.createdAt.getTime(),
        }
      : null,
  }
}
Example #14
Source File: index.ts    From reddium with MIT License 6 votes vote down vote up
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 #15
Source File: index.ts    From selftrace with MIT License 6 votes vote down vote up
// 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 #16
Source File: createApiHandler.ts    From ultimate-saas-ts with MIT License 6 votes vote down vote up
onError: ErrorHandler<NextApiRequest, NextApiResponse> = (
  err,
  req,
  res,
  next
) => {
  console.log(err);
  res.status(500).end(err.toString());
}
Example #17
Source File: import-events.ts    From website with MIT License 6 votes vote down vote up
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 #18
Source File: index.ts    From next-translate-routes with MIT License 6 votes vote down vote up
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 #19
Source File: index.ts    From core with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #20
Source File: [election_id].ts    From electify with MIT License 6 votes vote down vote up
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 #21
Source File: [word].ts    From crosshare with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #22
Source File: email.ts    From oxen-website with GNU General Public License v3.0 6 votes vote down vote up
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 #23
Source File: is-allowed-method.ts    From plasmic with MIT License 6 votes vote down vote up
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 #24
Source File: [donationId].tsx    From frontend with MIT License 6 votes vote down vote up
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 #25
Source File: email.tsx    From coindrop with GNU General Public License v3.0 6 votes vote down vote up
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 #26
Source File: subscribe.ts    From samuelkraft-next with MIT License 6 votes vote down vote up
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 #27
Source File: wrapExpressHandler.ts    From solana-pay with Apache License 2.0 6 votes vote down vote up
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();
                }
            });
        });
    };
}
Example #28
Source File: exit-preview.ts    From nextjs-bigcommerce-starter with MIT License 6 votes vote down vote up
export default async function exit(_: NextApiRequest, res: NextApiResponse) {
    // Exit the current user from "Preview Mode". This function accepts no args.
    res.clearPreviewData()

     // set the cookies to None
     const cookies = res.getHeader('Set-Cookie')
     if(cookies instanceof Array) {
        res.setHeader('Set-Cookie', cookies?.map((cookie: string) => cookie.replace('SameSite=Lax', 'SameSite=None')))
     }
 
    // Redirect the user back to the index page.
    res.redirect('/')
}
Example #29
Source File: [[...params]].ts    From next-api-decorators with MIT License 6 votes vote down vote up
NextAuthGuard = createMiddlewareDecorator(async (req: NextApiRequest, _res: NextApiResponse, next: NextFunction) => {
  const token = await getToken({ req, secret: process.env.JWT_SECRET });
  if (!token || !token.name) {
    throw new UnauthorizedException();
  }

  req.user = { name: token.name };
  next();
})