Created
June 27, 2022 15:46
-
-
Save polRk/7bc74e8383b2afa82ebe4714a4a063cb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import type { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda' | |
import { readFileSync } from 'node:fs' | |
import { resolve } from 'node:path' | |
import { render } from './entry-server' | |
import { getFormState, initYDB, NotFoundError } from './ydb' | |
import { configureStore } from '@reduxjs/toolkit' | |
import { AppMode, appReceived, formReceived, reducer } from './store' | |
initYDB().catch(console.error) | |
interface QueryParams { | |
target?: AppMode | |
channel_id?: string | |
contact_id?: string | |
form_id?: string | |
token?: string | |
} | |
// noinspection JSUnusedGlobalSymbols | |
export async function handler(event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> { | |
const { target, contact_id, form_id, token } = (event.queryStringParameters || {}) as QueryParams | |
if (!contact_id) { | |
return { | |
statusCode: 400, | |
body: '400 Bad Request: missing required query parameter: contact_id', | |
} | |
} | |
if (!form_id) { | |
return { | |
statusCode: 400, | |
body: '400 Bad Request: missing required query parameter: form_id', | |
} | |
} | |
const scripts: string[] = [] | |
if (target === 'webview') { | |
scripts.push('<script src="https://telegram.org/js/telegram-web-app.js"></script>') | |
scripts.push('<script>html.classList.add(window.Telegram.WebApp.colorScheme)</script>') | |
} | |
const store = configureStore({ reducer: reducer }) | |
await store.dispatch(appReceived({ mode: target || 'web', contactID: contact_id, formID: form_id })) | |
try { | |
const form = await getFormState(form_id, contact_id) | |
await store.dispatch(formReceived(form)) | |
const template = readFileSync(resolve(__dirname, '../client/index.html'), 'utf-8') | |
const html = template | |
.replace(`<!--ssr-csrf-token-->`, token || '') | |
.replace(`<!--ssr-scripts-->`, scripts.join('\n')) | |
.replace(`<!--ssr-html-->`, await render(store.getState())) | |
.replace(`<!--ssr-state-->`, JSON.stringify(store.getState()).replace(/</g, '\\u003c')) | |
return { | |
statusCode: 200, | |
headers: { | |
'Content-Type': 'text/html', | |
}, | |
body: html, | |
} | |
} catch (err) { | |
console.error(err) | |
// TODO: report to Sentry or similar | |
if (err instanceof NotFoundError) { | |
return { | |
statusCode: 404, | |
body: err.message, | |
} | |
} | |
return { | |
statusCode: 500, | |
body: err instanceof Error ? err.message : '500 Internal Server Error', | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment