next#NextApiHandler TypeScript Examples
The following examples show how to use
next#NextApiHandler.
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 plasmic with MIT License | 6 votes |
export function getEndpoint<
P extends APIProvider,
T extends GetAPISchema<any, any>
>(
commerce: CommerceAPI<P>,
context: T['endpoint'] & {
config?: P['config']
options?: T['schema']['endpoint']['options']
}
): NextApiHandler {
const cfg = commerce.getConfig(context.config)
return function apiHandler(req, res) {
return context.handler({
req,
res,
commerce,
config: cfg,
handlers: context.handlers,
options: context.options ?? {},
})
}
}
Example #2
Source File: setupServer.ts From next-api-decorators with MIT License | 6 votes |
export function setupServer(handler: NextApiHandler, disableBodyParser?: boolean): http.Server | express.Express {
if (process.env.TEST_SERVER === 'nextjs') {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
handler.config = { api: { bodyParser: !disableBodyParser } };
return http.createServer((req, res) => {
const parsedUrl = parse(req.url as any, true);
return apiResolver(req, res, parsedUrl.query, handler, {} as any, false);
});
}
return express()
.use(express.json())
.all('*', handler as any);
}
Example #3
Source File: create-api-handler.ts From nextjs-bigcommerce-starter with MIT License | 6 votes |
export default function createApiHandler<
T = any,
H extends BigcommerceHandlers = {},
Options extends {} = {}
>(
handler: BigcommerceApiHandler<T, H, Options>,
handlers: H,
defaultOptions: Options
) {
return function getApiHandler({
config,
operations,
options,
}: {
config?: BigcommerceConfig
operations?: Partial<H>
options?: Options extends {} ? Partial<Options> : never
} = {}): NextApiHandler {
const ops = { ...operations, ...handlers }
const opts = { ...defaultOptions, ...options }
return function apiHandler(req, res) {
return handler(req, res, getConfig(config), ops, opts)
}
}
}
Example #4
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();
}
});
});
};
}
Example #5
Source File: index.ts From solana-pay with Apache License 2.0 | 6 votes |
index: NextApiHandler<GetResponse | PostResponse> = async (request, response) => {
await cors(request, response);
await rateLimit(request, response);
if (request.method === 'GET') return get(request, response);
if (request.method === 'POST') return post(request, response);
throw new Error(`Unexpected method ${request.method}`);
}
Example #6
Source File: index.ts From solana-pay with Apache License 2.0 | 6 votes |
get: NextApiHandler<GetResponse> = async (request, response) => {
const label = request.query.label;
if (!label) throw new Error('missing label');
if (typeof label !== 'string') throw new Error('invalid label');
const icon = `https://${request.headers.host}/solana-pay-logo.svg`;
response.status(200).send({
label,
icon,
});
}
Example #7
Source File: delete.ts From coindrop with GNU General Public License v3.0 | 6 votes |
deleteUser: NextApiHandler = async (req: NextApiRequest, res: NextApiResponse) => {
try {
const uid = Array.isArray(req.headers.uid) ? req.headers.uid[0] : req.headers.uid;
await db().runTransaction(async (t) => {
const querySnapshot = await t.get(db().collection('piggybanks').where('owner_uid', '==', uid));
querySnapshot.forEach((doc) => {
t.delete(doc.ref);
});
t.delete(db().collection('users').doc(uid));
});
await admin.auth().deleteUser(uid);
return res.status(200).end();
} catch (err) {
return res.status(500).end();
}
}
Example #8
Source File: set-user-settings-for-existing-users.ts From coindrop with GNU General Public License v3.0 | 6 votes |
handler: NextApiHandler = async (req: NextApiRequest, res: NextApiResponse) => {
try {
initializeUserSettingsForExistingUsers();
res.status(200).end();
} catch (err) {
console.log(err);
res.status(500).end();
}
}
Example #9
Source File: get-email-list-subscribers.ts From coindrop with GNU General Public License v3.0 | 6 votes |
getEmailListSubscribers: NextApiHandler = async (req: NextApiRequest, res: NextApiResponse) => {
try {
const { listId }: { listId: EmailListIds } = req.body;
const ref = db()
.collection('users')
.where('email_lists', 'array-contains', listId);
const querySnapshot = await ref.get();
const emailAddresses = [];
querySnapshot.forEach(doc => {
emailAddresses.push(doc.data().email);
});
return res.status(200).send(emailAddresses.join('\n'));
} catch (err) {
console.log(err);
return res.status(400).end();
}
}
Example #10
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 #11
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 #12
Source File: index.ts From plasmic with MIT License | 6 votes |
createEndpoint =
<API extends GetAPISchema<any, any>>(endpoint: API['endpoint']) =>
<P extends APIProvider>(
commerce: CommerceAPI<P>,
context?: Partial<API['endpoint']> & {
config?: P['config']
options?: API['schema']['endpoint']['options']
}
): NextApiHandler => {
return getEndpoint(commerce, { ...endpoint, ...context })
}
Example #13
Source File: server.ts From mui-toolpad with MIT License | 6 votes |
export function createEndpoint(handlers: MethodMap): NextApiHandler {
return async (req, res): Promise<void> => {
const handler = handlers[req.method as Method];
if (handler) {
await handler(req, res);
return;
}
res.status(404).end();
};
}
Example #14
Source File: initMiddleware.ts From mui-toolpad with MIT License | 6 votes |
// Helper method to wait for a middleware to execute before continuing
// And to throw an error when an error happens in a middleware
export default function initMiddleware<T>(middleware: RequestHandler): NextApiHandler<T> {
return (req, res) =>
new Promise((resolve, reject) => {
middleware(req, res, (result: any) => {
if (result instanceof Error) {
return reject(result);
}
return resolve(result);
});
});
}
Example #15
Source File: server.ts From next-rpc with MIT License | 6 votes |
export function createRpcHandler(
methodsInit: [string, (...params: any[]) => Promise<any>][]
): NextApiHandler {
const methods = new Map(methodsInit);
return async (req, res) => {
if (req.method !== 'POST') {
sendError(res, 405, `method "${req.method}" is not allowed`);
return;
}
const { method, params } = req.body;
const requestedFn = methods.get(method);
if (typeof requestedFn !== 'function') {
sendError(res, 400, `"${method}" is not a function`);
return;
}
try {
const result = await requestedFn(...params);
return res.json({ result });
} catch (error) {
const {
name = 'NextRpcError',
message = `Invalid value thrown in "${method}", must be instance of Error`,
stack = undefined,
} = error instanceof Error ? error : {};
return res.json({
error: {
name,
message,
stack: process.env.NODE_ENV === 'production' ? undefined : stack,
},
});
}
};
}
Example #16
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 #17
Source File: errorMiddleware.ts From excalidraw-json with MIT License | 6 votes |
export function errorMiddleware<Request extends NextApiRequest, T = any>(
handler: (
req: Request,
res: NextApiResponse<T>,
) => ReturnType<NextApiHandler>,
): (req: Request, res: NextApiResponse<T>) => ReturnType<NextApiHandler> {
return async (req, res) => {
try {
return await handler(req, res);
} catch (error) {
if (!isBoom(error)) {
throw error;
}
const { statusCode, payload } = error.output;
res.status(statusCode);
res.json(payload as any);
}
};
}
Example #18
Source File: httpMethodRouter.ts From excalidraw-json with MIT License | 6 votes |
// See https://github.com/jamo/micro-method-router/blob/3c355c2/index.js
export function httpMethodRouter<
Request extends NextApiRequest = NextApiRequest,
Response = any
>(
map: RouterMap<Request, Response>,
): (
req: Request,
res: NextApiResponse<Response>,
) => ReturnType<NextApiHandler> {
const defaultMap: RouterMap = {
OPTIONS: (_req, res) => {
res.setHeader('Allow', allowedVerbs);
res.end();
},
};
const finalMap = { ...defaultMap, ...map };
const allowedVerbs = Object.keys(finalMap)
.map((v) => v.toUpperCase())
.join(', ');
return (req, res) => {
const method = (req.method ?? 'GET').toUpperCase() as HttpMethods;
const fn = finalMap[method];
if (!fn) {
res.setHeader('Allow', allowedVerbs);
throw methodNotAllowed(`Method ${method} not allowed.`);
}
return fn(req, res);
};
}
Example #19
Source File: create-api-handler.ts From storefront-data-hooks with MIT License | 6 votes |
export default function createApiHandler<
T = any,
H extends BigcommerceHandlers = {},
Options extends {} = {}
>(
handler: BigcommerceApiHandler<T, H, Options>,
handlers: H,
defaultOptions: Options
) {
return function getApiHandler({
config,
operations,
options,
}: {
config?: BigcommerceConfig
operations?: Partial<H>
options?: Options extends {} ? Partial<Options> : never
} = {}): NextApiHandler {
const ops = { ...handlers, ...operations }
const opts = { ...defaultOptions, ...options }
return function apiHandler(req, res) {
return handler(req, res, getConfig(config), ops, opts)
}
}
}
Example #20
Source File: logout.tsx From hakka with MIT License | 6 votes |
handler: NextApiHandler = (req, res) => {
const authCookie = serialize(AUTH_COOKIE_NAME, '', {
path: '/',
httpOnly: true,
sameSite: 'lax',
maxAge: 0,
})
res.setHeader('Set-Cookie', [authCookie])
res.redirect('/login')
}
Example #21
Source File: graphql.ts From hakka with MIT License | 6 votes |
apiHandler: NextApiHandler = async (req, res) => {
if (handler && isProd) {
return handler(req, res)
}
const schema = await getSchema()
const apolloServer = new ApolloServer({
schema,
tracing: !isProd,
playground: {
settings: {
'request.credentials': 'include',
},
},
introspection: true,
async context({ req, res }) {
const { user } = await getServerSession(req)
return {
req,
res,
user,
}
},
})
handler = apolloServer.createHandler({
path: `/api/graphql`,
})
return handler(req, res)
}
Example #22
Source File: rpc.ts From mui-toolpad with MIT License | 6 votes |
function createRpcHandler(definition: Definition): NextApiHandler<RpcResponse> {
return async (req, res) => {
if (req.method !== 'POST') {
res.status(405).end();
return;
}
const { type, name, params } = req.body as RpcRequest;
if (!hasOwnProperty(definition, type) || !hasOwnProperty(definition[type], name)) {
// This is important to avoid RCE
res.status(404).end();
return;
}
const method: MethodResolver<any> = definition[type][name];
const context = { req, res };
let rawResult;
try {
rawResult = await method(params, context);
} catch (error) {
if (error instanceof Error) {
res.json({ error: { message: error.message, stack: error.stack } });
} else {
res.status(500).end();
}
return;
}
const responseData: RpcResponse = { result: superjson.stringify(rawResult) };
res.json(responseData);
};
}
Example #23
Source File: top-tracks.ts From dhafit.xyz with MIT License | 6 votes |
handler: NextApiHandler = async (req, res) => {
if (req.method === "GET") {
try {
const response = await getTopTracks();
const { items } = await response.json();
const tracks = await items.slice(0, 10).map((track: SpotifyTrack) => ({
album: track.album.name,
albumImageUrl: track.album.images[0].url,
artist: track.artists.map((_artist) => _artist.name).join(", "),
title: track.name,
duration: track.duration_ms,
songUrl: track.external_urls.spotify,
}));
return res.status(200).json({ tracks });
} catch (err: unknown) {
console.log(err);
return res.status(400).json({ message: "An error occured" });
}
}
return res.status(404).json({ message: "Not found" });
}
Example #24
Source File: feed.ts From hakka with MIT License | 5 votes |
handler: NextApiHandler = async (req, res) => {
const feed = new Feed({
id: 'https://hakka.dev',
title: 'HAKKA!',
copyright: 'HAKKA! all rights reserved',
link: 'https://hakka.dev',
})
const topics = await prisma.topic.findMany({
where: {
hidden: null,
},
orderBy: {
createdAt: 'desc',
},
take: 30,
include: {
author: true,
},
})
for (const topic of topics) {
feed.addItem({
title: topic.title,
id: `topic:${topic.id}`,
date: topic.updatedAt,
published: topic.createdAt,
link: `https://hakka.dev/t/${topic.id}`,
author: [
{
name: topic.author.username,
},
],
extensions: [
{
name: 'external_link',
objects: topic.url,
},
],
})
}
res.setHeader('Content-Type', 'application/json')
res.end(feed.json1())
}
Example #25
Source File: createHandler.ts From next-api-decorators with MIT License | 5 votes |
/**
* Prepares a router for the given class.
*
* @param cls Router class
*
* @example
* ```ts
* import { createHandler, Get } from '@storyofams/next-api-decorators';
*
* class Events {
* Get()
* public events() {
* return DB.findEvents();
* }
* }
*
* export default createHandler(Events);
* ```
*/
export function createHandler(cls: new (...args: any[]) => any): NextApiHandler {
const instance = new cls();
const [directory, fileName] = getCallerInfo();
return (req: NextApiRequest, res: NextApiResponse) => {
if (!req.url || !req.method) {
return notFound(req, res);
}
const path = parseRequestUrl(req, directory, fileName);
const [keys, match, method] = findRoute(cls, req.method, path);
if (!method) {
return notFound(req, res);
}
const methodFn = instance[method.propertyKey];
if (!methodFn) {
return notFound(req, res);
}
req.params = getParams(keys, match);
return methodFn.call(instance, req, res);
};
}
Example #26
Source File: index.ts From solana-pay with Apache License 2.0 | 5 votes |
post: NextApiHandler<PostResponse> = async (request, response) => {
/*
Transfer request params provided in the URL by the app client. In practice, these should be generated on the server,
persisted along with an unpredictable opaque ID representing the payment, and the ID be passed to the app client,
which will include the ID in the transaction request URL. This prevents tampering with the transaction request.
*/
const recipientField = request.query.recipient;
if (!recipientField) throw new Error('missing recipient');
if (typeof recipientField !== 'string') throw new Error('invalid recipient');
const recipient = new PublicKey(recipientField);
const amountField = request.query.amount;
if (!amountField) throw new Error('missing amount');
if (typeof amountField !== 'string') throw new Error('invalid amount');
const amount = new BigNumber(amountField);
const splTokenField = request.query['spl-token'];
if (splTokenField && typeof splTokenField !== 'string') throw new Error('invalid spl-token');
const splToken = splTokenField ? new PublicKey(splTokenField) : undefined;
const referenceField = request.query.reference;
if (!referenceField) throw new Error('missing reference');
if (typeof referenceField !== 'string') throw new Error('invalid reference');
const reference = new PublicKey(referenceField);
const memoParam = request.query.memo;
if (memoParam && typeof memoParam !== 'string') throw new Error('invalid memo');
const memo = memoParam || undefined;
const messageParam = request.query.message;
if (messageParam && typeof messageParam !== 'string') throw new Error('invalid message');
const message = messageParam || undefined;
// Account provided in the transaction request body by the wallet.
const accountField = request.body?.account;
if (!accountField) throw new Error('missing account');
if (typeof accountField !== 'string') throw new Error('invalid account');
const account = new PublicKey(accountField);
// Compose a simple transfer transaction to return. In practice, this can be any transaction, and may be signed.
let transaction = await createTransfer(connection, account, {
recipient,
amount,
splToken,
reference,
memo,
});
// Serialize and deserialize the transaction. This ensures consistent ordering of the account keys for signing.
transaction = Transaction.from(
transaction.serialize({
verifySignatures: false,
requireAllSignatures: false,
})
);
// Serialize and return the unsigned transaction.
const serialized = transaction.serialize({
verifySignatures: false,
requireAllSignatures: false,
});
const base64 = serialized.toString('base64');
response.status(200).send({ transaction: base64, message });
}
Example #27
Source File: send-welcome-email.tsx From coindrop with GNU General Public License v3.0 | 5 votes |
sendWelcomeEmail: NextApiHandler = async (req: NextApiRequest, res: NextApiResponse) => {
try {
const { email } = req.body;
const Body: FC = () => (
<>
<Paragraph>
Coindrop's mission is to make it easy to receive tips and donations anywhere.
</Paragraph>
<Paragraph>
As you begin to use Coindrop, I'd love to hear your feedback. What could be improved? You can reply directly to any of our e-mails.
</Paragraph>
<Paragraph>
Coindrop is 100% open-source on <a href={githubUrl} style={{color: "gray"}}>Github</a> so any contributions and ideas are open and welcome.
</Paragraph>
<Paragraph>
Thanks and enjoy zero-fee payments!
</Paragraph>
<Paragraph>
- Mark Jackson, Founder of Coindrop
</Paragraph>
</>
);
const html = generateStaticHTML({
title: "Welcome!",
previewText: "A few things to note as you get started",
Body,
userEmail: email,
emailListId: null,
});
await sesSend({
to: email,
subject: 'Welcome to Coindrop',
html,
});
return res.status(200).end();
} catch (err) {
console.error(err);
return res.status(500).send(err.stack); // TODO: don't send full stack normally, only for testing
}
}
Example #28
Source File: [...nextauth].ts From ultimate-saas-ts with MIT License | 5 votes |
authHandler: NextApiHandler = (req, res) => NextAuth(req, res, options)
Example #29
Source File: 429.ts From core with GNU Affero General Public License v3.0 | 5 votes |
RateLimit: NextApiHandler = (_req: NextApiRequest, res: NextApiResponse) => {
res.statusCode = 429
return ResponseWrapper(res, {
code: 429,
message: '지정된 시간에 너무 많은 요청을 보냈습니다. 잠시 뒤에 시도해주세요.',
errors: ['지정된 시간에 너무 많은 요청을 보냈습니다. 잠시 뒤에 시도해주세요.'],
})
}