repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
generative-ai-application-builder-on-aws | github_2023 | aws-solutions | typescript | isPromptTemplatePresentOnce | const isPromptTemplatePresentOnce = (sagemakerInputSchema: string): boolean => {
const matches = new RegExp(PROMPT_SCHEMA_REGEX).exec(sagemakerInputSchema);
return matches !== null && matches?.length === 1;
}; | /**
* Checks if only the prompt template string is present only once in the template
* @param matches regex match result for the prompt input template string
* @returns
*/ | https://github.com/aws-solutions/generative-ai-application-builder-on-aws/blob/b278845810db549e19740c5a2405faee959b82a3/source/ui-deployment/src/components/wizard/Model/SagemakerPayloadSchema/InputSchema.tsx#L69-L72 | b278845810db549e19740c5a2405faee959b82a3 |
generative-ai-application-builder-on-aws | github_2023 | aws-solutions | typescript | validateDisambiguationPrompt | const validateDisambiguationPrompt = (promptTemplate: string, maxPromptLength: number): string => {
let error = '';
const requiredPlaceholders = ['{input}', '{history}'];
if (!promptTemplate) {
return 'Enter a valid prompt template';
}
if (promptTemplate.length > maxPromptLength) {
return `The prompt template has too many characters. Character count: ${promptTemplate.length}/${maxPromptLength}`;
}
for (const placeholder of requiredPlaceholders) {
if (!promptTemplate.includes(placeholder)) {
return `Missing required placeholder '${placeholder}'. See info panel for help or reset prompt template to default.`;
}
//placeholder should exist only once in promptTemplate
if (promptTemplate.indexOf(placeholder) !== promptTemplate.lastIndexOf(placeholder)) {
return `Placeholder '${placeholder}' should appear only once in the prompt template. See info panel for help or reset prompt template to default.`;
}
}
return error;
}; | //validates the user-provided prompt template to ensure it meets the required criteria. | https://github.com/aws-solutions/generative-ai-application-builder-on-aws/blob/b278845810db549e19740c5a2405faee959b82a3/source/ui-deployment/src/components/wizard/Prompt/DisambiguationPromptConfiguration.tsx#L130-L154 | b278845810db549e19740c5a2405faee959b82a3 |
arduino-littlefs-upload | github_2023 | earlephilhower | typescript | runCommand | async function runCommand(exe : string, opts : any[]) {
const cmd = spawn(exe, opts);
for await (const chunk of cmd.stdout) {
writeEmitter.fire(String(chunk).replace(/\n/g, "\r\n"));
}
for await (const chunk of cmd.stderr) {
// Write stderr in red
writeEmitter.fire("\x1b[31m" + String(chunk).replace(/\n/g, "\r\n") + "\x1b[0m");
}
// Wait until the executable finishes
let exitCode = await new Promise( (resolve, reject) => {
cmd.on('close', resolve);
});
return exitCode;
} | // Execute a command and display it's output in the terminal | https://github.com/earlephilhower/arduino-littlefs-upload/blob/4c74c4c34517dc32510bf231be27654884373ecb/src/extension.ts#L112-L126 | 4c74c4c34517dc32510bf231be27654884373ecb |
horizon-tailwind-react-nextjs | github_2023 | horizon-ui | typescript | handleClickOutside | function handleClickOutside(event: any) {
if (ref.current && !ref.current.contains(event.target)) {
setX(false);
}
} | /**
* Alert if clicked on outside of element
*/ | https://github.com/horizon-ui/horizon-tailwind-react-nextjs/blob/2f65f2112a3b04cdf28571f4f1ba48ad83d9ee24/src/components/dropdown/index.tsx#L9-L13 | 2f65f2112a3b04cdf28571f4f1ba48ad83d9ee24 |
lowflow-design | github_2023 | tsai996 | typescript | RequestHttp.constructor | public constructor(config: AxiosRequestConfig) {
this.service = axios.create(config)
this.service.interceptors.request.use(
(config: InternalAxiosRequestConfig) => {
return config
},
(error: AxiosError) => {
return Promise.reject(error)
}
)
this.service.interceptors.response.use(
(response: AxiosResponse) => {
const { data } = response
return data
},
(error: AxiosError) => {
const { response, message } = error
const data = response?.data as ResultData
const errMsg = data ? data.message : message
ElNotification.error(errMsg || '未知错误')
return Promise.reject(response?.data || error)
}
)
} | /**
* 请求构造函数
* @param config
*/ | https://github.com/tsai996/lowflow-design/blob/ec6aa60a549c7204b48c5e436a2c392310f1684c/src/api/index.ts#L35-L58 | ec6aa60a549c7204b48c5e436a2c392310f1684c |
lowflow-design | github_2023 | tsai996 | typescript | RequestHttp.get | get<T>(url: string, params?: object, config = {}): Promise<ResultData<T>> {
return this.service.get(url, { params, ...config })
} | /**
* get请求
* @param url
* @param params
* @param config
*/ | https://github.com/tsai996/lowflow-design/blob/ec6aa60a549c7204b48c5e436a2c392310f1684c/src/api/index.ts#L66-L68 | ec6aa60a549c7204b48c5e436a2c392310f1684c |
lowflow-design | github_2023 | tsai996 | typescript | RequestHttp.post | post<T>(url: string, data?: object, config = {}): Promise<ResultData<T>> {
return this.service.post(url, data, config)
} | /**
* post请求
* @param url
* @param data
* @param config
*/ | https://github.com/tsai996/lowflow-design/blob/ec6aa60a549c7204b48c5e436a2c392310f1684c/src/api/index.ts#L76-L78 | ec6aa60a549c7204b48c5e436a2c392310f1684c |
lowflow-design | github_2023 | tsai996 | typescript | RequestHttp.request | request<T>(config: AxiosRequestConfig): Promise<ResultData<T>> {
return this.service.request(config)
} | /**
* request请求
* @param config
*/ | https://github.com/tsai996/lowflow-design/blob/ec6aa60a549c7204b48c5e436a2c392310f1684c/src/api/index.ts#L84-L86 | ec6aa60a549c7204b48c5e436a2c392310f1684c |
lowflow-design | github_2023 | tsai996 | typescript | RequestHttp.download | download(url: string, data?: object, config = {}): Promise<BlobPart> {
return this.service.post(url, data, { ...config, responseType: 'blob' })
} | /**
* 下载文件
* @param url
* @param data
* @param config
*/ | https://github.com/tsai996/lowflow-design/blob/ec6aa60a549c7204b48c5e436a2c392310f1684c/src/api/index.ts#L94-L96 | ec6aa60a549c7204b48c5e436a2c392310f1684c |
lowflow-design | github_2023 | tsai996 | typescript | buildProps | const buildProps = (fieldClone: Field) => {
const dataObject: Record<string, any> = {}
const _props = fieldClone.props || {}
Object.keys(_props).forEach((key) => {
dataObject[key] = _props[key]
})
if (props.modelValue !== undefined) {
dataObject.modelValue = props.modelValue
} else {
dataObject.modelValue = fieldClone.value
}
dataObject['onUpdate:modelValue'] = (value: any) => {
emit('update:modelValue', value)
}
delete dataObject.options
return dataObject
} | /**
* 构建属性参数
* @param fieldClone
*/ | https://github.com/tsai996/lowflow-design/blob/ec6aa60a549c7204b48c5e436a2c392310f1684c/src/components/Render/index.tsx#L38-L54 | ec6aa60a549c7204b48c5e436a2c392310f1684c |
lowflow-design | github_2023 | tsai996 | typescript | buildSlots | const buildSlots = (fieldClone: Field) => {
const children: Record<string, any> = {}
const slotFunctions: Record<string, any> = {
ElSelect: (conf: Field) => {
return conf.props.options.map((item: any) => {
return <el-option label={item.label} value={item.value}></el-option>
})
},
ElRadio: (conf: Field) => {
return conf.props.options.map((item: any) => {
return <el-radio label={item.value}>{item.label}</el-radio>
})
},
ElCheckbox: (conf: Field) => {
return conf.props.options.map((item: any) => {
return <el-checkbox label={item.value}>{item.label}</el-checkbox>
})
}
}
const slotFunction = slotFunctions[fieldClone.name]
if (slotFunction) {
children.default = () => {
return slotFunction(fieldClone)
}
}
return children
} | /**
* 构建插槽
* @param fieldClone
*/ | https://github.com/tsai996/lowflow-design/blob/ec6aa60a549c7204b48c5e436a2c392310f1684c/src/components/Render/index.tsx#L59-L85 | ec6aa60a549c7204b48c5e436a2c392310f1684c |
compass | github_2023 | SwitchbackTech | typescript | _flatten | const _flatten = (obj: object, out: object) => {
Object.keys(obj).forEach((key) => {
if (typeof obj[key] == "object") {
out = _flatten(obj[key], out); // recursively call for nesteds
} else {
out[key] = obj[key]; // direct assign for values
}
});
return out;
}; | /* useful for deeply nested objects, like Mongo filters */ | https://github.com/SwitchbackTech/compass/blob/39f95d92905a778bc07be73179d347e72aa6f0e3/packages/backend/src/__tests__/event.find/event.find.test.ts#L280-L289 | 39f95d92905a778bc07be73179d347e72aa6f0e3 |
compass | github_2023 | SwitchbackTech | typescript | EventService.deleteAllByUser | deleteAllByUser = async (userId: string) => {
const response = await mongoService.db
.collection(Collections.EVENT)
.deleteMany({ user: userId });
return response;
} | /*
Deletes all of a user's events
REMINDER: this should only delete a user's *Compass* events --
don't ever delete their events in gcal or any other 3rd party calendar
*/ | https://github.com/SwitchbackTech/compass/blob/39f95d92905a778bc07be73179d347e72aa6f0e3/packages/backend/src/event/services/event.service.ts | 39f95d92905a778bc07be73179d347e72aa6f0e3 |
compass | github_2023 | SwitchbackTech | typescript | _createGcalEvent | const _createGcalEvent = async (userId: string, event: Schema_Event_Core) => {
const _gEvent = MapEvent.toGcal(event);
const gcal = await getGcalClient(userId);
const gEvent = await gcalService.createEvent(gcal, _gEvent);
return gEvent;
}; | /**********
* Helpers
* (that have too many dependencies
* to put in event.service.util)
*********/ | https://github.com/SwitchbackTech/compass/blob/39f95d92905a778bc07be73179d347e72aa6f0e3/packages/backend/src/event/services/event.service.ts#L367-L374 | 39f95d92905a778bc07be73179d347e72aa6f0e3 |
compass | github_2023 | SwitchbackTech | typescript | _isntBeingDeleted | const _isntBeingDeleted = (e: gSchema$Event) =>
!toDelete.includes(e.id as string); | // if its going to be deleted anyway, then dont bother updating | https://github.com/SwitchbackTech/compass/blob/39f95d92905a778bc07be73179d347e72aa6f0e3/packages/backend/src/sync/util/sync.utils.ts#L62-L63 | 39f95d92905a778bc07be73179d347e72aa6f0e3 |
compass | github_2023 | SwitchbackTech | typescript | _usesDashesCorrectly | const _usesDashesCorrectly = (dateStr) => {
expect(dateStr[4]).toBe("-");
expect(dateStr[7]).toBe("-");
}; | // ensures YYYY-MM-DD format | https://github.com/SwitchbackTech/compass/blob/39f95d92905a778bc07be73179d347e72aa6f0e3/packages/core/src/__tests__/mappers/map.event.test.ts#L13-L16 | 39f95d92905a778bc07be73179d347e72aa6f0e3 |
compass | github_2023 | SwitchbackTech | typescript | _hasTzOffset | const _hasTzOffset = (dateStr) => ["-", "+"].includes(dateStr[19]); | // confirms the expected offset/timezone indicator char is in the string | https://github.com/SwitchbackTech/compass/blob/39f95d92905a778bc07be73179d347e72aa6f0e3/packages/core/src/__tests__/mappers/map.event.test.ts#L31-L31 | 39f95d92905a778bc07be73179d347e72aa6f0e3 |
compass | github_2023 | SwitchbackTech | typescript | snapYToGrid | const snapYToGrid = (
cursorY: number,
measurements: Measurements_Grid,
scrollTop: number
): number => {
if (!measurements.mainGrid) return cursorY; // TS guard
// Calculate the cursor's Y position relative to the grid's top and account for scrolling
const gridY = cursorY - measurements.mainGrid.top + scrollTop;
// Convert the grid time interval to a fractional hour (assuming GRID_TIME_STEP is in minutes and will never be larger than 60)
const fractionalHour = GRID_TIME_STEP / 60;
// Calculate the height of a single grid time interval in pixels
const intervalHeightInPixels = measurements.hourHeight * fractionalHour;
// Snap the relative Y position to the nearest grid interval
const snappedRelativeY = roundToPrev(gridY, intervalHeightInPixels);
// Adjust snappedY to position the event relative to the page's viewport
const snappedY = snappedRelativeY + measurements.mainGrid.top - scrollTop;
return snappedY;
}; | // TODO: Draw a step by step diagram to explain how the snapping works? (Might | https://github.com/SwitchbackTech/compass/blob/39f95d92905a778bc07be73179d347e72aa6f0e3/packages/web/src/views/Calendar/components/Event/Grid/GridEventPreview/snap.grid.ts#L19-L42 | 39f95d92905a778bc07be73179d347e72aa6f0e3 |
compass | github_2023 | SwitchbackTech | typescript | convertSomedayDraftToTimed | const convertSomedayDraftToTimed = (
dropItem: DropResult_ReactDND,
dates: { startDate: string; endDate: string }
) => {
const event = prepEvtAfterDraftDrop(
Categories_Event.TIMED,
dropItem,
dates
);
dispatch(createEventSlice.actions.request(event));
dispatch(draftSlice.actions.discard());
}; | // call this when enabling DND for drafts | https://github.com/SwitchbackTech/compass/blob/39f95d92905a778bc07be73179d347e72aa6f0e3/packages/web/src/views/Calendar/hooks/draft/sidebar/useSidebarUtil.ts#L86-L98 | 39f95d92905a778bc07be73179d347e72aa6f0e3 |
trpc-crdt | github_2023 | KyleAMathews | typescript | handleCall | async function handleCall(callObj: CallObj) {
if (requestSet.has(callObj.id)) {
return
} else {
requestSet.add(callObj.id)
}
const transactionFns: any[] = []
const transact = (fn: () => void) => {
transactionFns.push(fn)
}
try {
const response = await callProcedure({
procedures: appRouter._def.procedures,
path: callObj.path,
rawInput: JSON.parse(callObj.input),
type: callObj.type,
ctx: { ...context, transact },
})
const transactionPromises = transactionFns.map((fn) => fn())
// This won't happen in the same transaction but because they run
// simultaneously, they should be synced back to postgres at the same time (I think).
await Promise.all([
...transactionPromises,
db.trpc_calls.update({
data: {
state: `DONE`,
response: JSON.stringify(response),
},
where: {
id: callObj.id,
},
}),
])
await electric.notifier.potentiallyChanged()
} catch (cause) {
const error = getTRPCErrorFromUnknown(cause)
const errorShape = getErrorShape({
config: appRouter._def._config,
error,
type: callObj.type,
path: callObj.path,
input: JSON.parse(callObj.input),
ctx: context,
})
onError?.({
error,
type: callObj.type,
path: callObj.path,
input: JSON.parse(callObj.input),
ctx: context,
})
try {
await db.trpc_calls.update({
data: {
state: `ERROR`,
response: JSON.stringify({ error: errorShape }),
},
where: {
id: callObj.id,
},
})
} catch (e) {
console.log(`error update failed`, e)
}
}
} | // Handle new tRPC calls. | https://github.com/KyleAMathews/trpc-crdt/blob/66101999c0d652ce9f2c69d0b41ff65a2cd95a24/packages/electric-sql/src/adapter.ts#L50-L121 | 66101999c0d652ce9f2c69d0b41ff65a2cd95a24 |
trpc-crdt | github_2023 | KyleAMathews | typescript | call | async function call() {
await db.trpc_calls.create({
data: {
id: callId,
path,
input: JSON.stringify(input),
type,
state: `WAITING`,
createdat: new Date(),
clientid: clientId,
},
})
} | // Create trpc_call row — this will get replicated to the server | https://github.com/KyleAMathews/trpc-crdt/blob/66101999c0d652ce9f2c69d0b41ff65a2cd95a24/packages/electric-sql/src/link.ts#L120-L132 | 66101999c0d652ce9f2c69d0b41ff65a2cd95a24 |
trpc-crdt | github_2023 | KyleAMathews | typescript | observe | function observe(event: YMapEvent<any>) {
const state = event.target
if (state.get(`state`) !== `WAITING` && state.get(`id`) === callId) {
callMap.unobserve(observe)
callMap.set(
`elapsedMs`,
new Date().getTime() -
new Date((callMap.get(`createdAt`) as number) || 0).getTime()
)
if (state.get(`state`) === `ERROR`) {
observer.error(TRPCClientError.from(state.get(`response`)))
} else if (state.get(`state`) === `DONE`) {
observer.next({
result: {
type: `data`,
data: state.get(`response`),
},
})
}
observer.complete()
}
} | // The observe function to listen to the response | https://github.com/KyleAMathews/trpc-crdt/blob/66101999c0d652ce9f2c69d0b41ff65a2cd95a24/packages/yjs/src/link.ts#L42-L63 | 66101999c0d652ce9f2c69d0b41ff65a2cd95a24 |
telebook | github_2023 | neSpecc | typescript | handleBrokenVariables | function handleBrokenVariables(): void {
const themeBgColor = getCSSVariable('--tg-theme-bg-color')
const themeSecondaryBgColor = getCSSVariable('--tg-theme-secondary-bg-color')
if (themeBgColor === '#000000' && themeSecondaryBgColor !== '#000000') {
document.documentElement.style.setProperty('--tg-theme-bg-color', themeSecondaryBgColor ?? '')
document.documentElement.style.setProperty('--tg-theme-secondary-bg-color', themeBgColor ?? '')
return
}
/**
* Workaround problem with iOS Dark Dimmed theme. Manually make secondary bg color darker
*/
if (themeBgColor === themeSecondaryBgColor && themeBgColor !== undefined) {
document.documentElement.style.setProperty('--tg-theme-secondary-bg-color', darkenColor(themeBgColor, 2.3))
}
} | /**
* In the last Telegram iOS client, some theme variable are broken in Dark mode:
* --tg-theme-bg-color (used for island in docs) became #000000
* --tg-theme-secondary-bg-color (used for app bg in docs) became lighter that the --tg-theme-bg-color
*
* As a temporary workaround, we check if the variables are broken and swap them
*
* Another issue we have in iOS Dark Dimmed theme: both variables are the same, so we manually change one of them
*
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/main.ts#L56-L73 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | lock | function lock(): void {
document.body.style.overflow = 'hidden'
} | /**
* Lock the scroll
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/application/services/useScroll.ts#L25-L27 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | unlock | function unlock(): void {
document.body.style.overflow = 'unset'
} | /**
* Unlock the scroll
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/application/services/useScroll.ts#L32-L34 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | scrollTo | function scrollTo(el: HTMLElement, offset = 0): void {
window.scrollTo({
top: el.offsetTop - offset,
behavior: 'smooth',
})
} | /**
* Scroll to element
*
* @param el The element to scroll to
* @param offset The offset to scroll to
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/application/services/useScroll.ts#L42-L47 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | prepareDebugButton | function prepareDebugButton(reference: Ref<any>, className: string): void {
if (WebApp.platform !== 'unknown') {
return
}
if (reference.value !== undefined) {
return
}
const button = document.createElement('button')
button.classList.add(className)
document.body.appendChild(button)
reference.value = button
} | /**
* When we debug the app in the browser, we need to create a fake main button
*
* @param reference The reference to store the button
* @param className The class name to add to the button
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/application/services/useTelegram.ts#L48-L62 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | showMainButton | function showMainButton(text: string, callback: () => void): void {
prepareDebugButton(debugMainButton, 'fake-main-button')
if (mainButtonCallback.value !== null) {
WebApp.MainButton.offClick(mainButtonCallback.value)
}
mainButtonCallback.value = callback
WebApp.MainButton.text = text ?? 'Submit'
WebApp.MainButton.onClick(mainButtonCallback.value)
WebApp.MainButton.isVisible = true
if (debugMainButton.value !== undefined) {
debugMainButton.value.innerText = text ?? 'Submit'
debugMainButton.value.addEventListener('click', mainButtonCallback.value)
debugMainButton.value.classList.add('visible')
}
} | /**
* Show the main button
*
* @param text The text to show on the button
* @param callback The callback to call when the button is clicked
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/application/services/useTelegram.ts#L70-L88 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | hideMainButton | function hideMainButton(): void {
if (mainButtonCallback.value === null) {
console.warn('Trying to hide main button but no callback was set')
return
}
WebApp.MainButton.offClick(mainButtonCallback.value)
debugMainButton.value?.removeEventListener('click', mainButtonCallback.value)
mainButtonCallback.value = null
WebApp.MainButton.isVisible = false
debugMainButton.value?.classList.remove('visible')
} | /**
* Hide the main button
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/application/services/useTelegram.ts#L93-L105 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | showBackButton | function showBackButton(callback: () => void): void {
prepareDebugButton(debugBackButton, 'fake-back-button')
if (backButtonCallback.value !== null) {
WebApp.BackButton.offClick(backButtonCallback.value)
}
backButtonCallback.value = callback
WebApp.BackButton.onClick(backButtonCallback.value)
WebApp.BackButton.show()
if (debugBackButton.value !== undefined) {
debugBackButton.value.innerText = '‹ Back'
debugBackButton.value.addEventListener('click', backButtonCallback.value)
debugBackButton.value.classList.add('visible')
}
} | /**
* Show the back button
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/application/services/useTelegram.ts#L110-L127 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | hideBackButton | function hideBackButton(): void {
if (backButtonCallback.value === null) {
console.warn('Trying to hide back button but no callback was set')
return
}
WebApp.BackButton.offClick(backButtonCallback.value)
debugBackButton.value?.removeEventListener('click', backButtonCallback.value)
backButtonCallback.value = null
WebApp.BackButton.hide()
debugBackButton.value?.classList.remove('visible')
} | /**
* Hide the back button
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/application/services/useTelegram.ts#L132-L144 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | setButtonLoader | function setButtonLoader(state: boolean): void {
if (state) {
WebApp.MainButton.showProgress()
} else {
WebApp.MainButton.hideProgress()
}
} | /**
* Show/hide the main button loader
*
* @param state The state to set the loader to
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/application/services/useTelegram.ts#L151-L157 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | showAlert | function showAlert(text: string): void {
WebApp.showAlert(text)
} | /**
* Shows native Telegram alert message
*
* @param text The text to show in the alert
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/application/services/useTelegram.ts#L164-L166 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | openInvoice | function openInvoice(url: string, callback: (status: 'pending' | 'failed' | 'cancelled' | 'paid') => void): void {
WebApp.openInvoice(url, callback)
} | /**
* Opens Telegram invoice
*
* @param url The invoice URL
* @param callback The callback to call when the invoice is paid
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/application/services/useTelegram.ts#L174-L176 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | closeApp | function closeApp(): void {
WebApp.close()
} | /**
* Closes the app
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/application/services/useTelegram.ts#L181-L183 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | expand | function expand(): void {
WebApp.expand()
} | /**
* Expands Telegram app layout
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/application/services/useTelegram.ts#L188-L190 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | getViewportHeight | function getViewportHeight(): number {
return WebApp.viewportStableHeight
} | /**
*
* The current height of the visible area of the Mini App. Also available in CSS as the variable var(--tg-viewport-height).
* The application can display just the top part of the Mini App, with its lower part remaining outside the screen area.
* From this position, the user can “pull” the Mini App to its maximum height, while the bot can do the same by calling the expand() method.
* As the position of the Mini App changes, the current height value of the visible area will be updated in real time.
* Please note that the refresh rate of this value is not sufficient to smoothly follow the lower border of the window.
* It should not be used to pin interface elements to the bottom of the visible area.
* It's more appropriate to use the value of the viewportStableHeight field for this purpose.
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/application/services/useTelegram.ts#L202-L204 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | vibrate | function vibrate(style: 'light' | 'medium' | 'heavy' | 'rigid' | 'soft' | 'error' | 'warning' | 'success' = 'heavy'): void {
switch (style) {
case 'light':
case 'medium':
case 'heavy':
case 'rigid':
case 'soft':
WebApp.HapticFeedback.impactOccurred(style)
break
case 'error':
case 'warning':
case 'success':
WebApp.HapticFeedback.notificationOccurred(style)
break
}
} | /**
* Vibrate the device
*
* @param style The style of the vibration
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/application/services/useTelegram.ts#L211-L226 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | ready | function ready(): void {
WebApp.ready()
} | /**
* Tells Telegram
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/application/services/useTelegram.ts#L231-L233 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | setHeaderColor | function setHeaderColor(color: 'bg_color' | 'secondary_bg_color' | `#${string}`): void {
WebApp.setHeaderColor(color)
} | /**
* Sets the header color of the app wrapper
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/application/services/useTelegram.ts#L238-L240 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | NotFoundError.constructor | constructor(message: string = 'NotFound') {
super(message)
this.name = 'NotFoundError'
} | /**
* Constructor for NotFound error
*
* @param message - Error message
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/domain/entities/errors/NotFound.ts#L12-L15 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | UnauthorizedError.constructor | constructor(message: string = 'Unauthorized') {
super(message)
this.name = 'UnauthorizedError'
} | /**
* Constructor for unauthorized error
*
* @param message - Error message
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/domain/entities/errors/Unauthorized.ts#L12-L15 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | create | const create = async (params: CreateInvoiceParams): Promise<string | null> => {
try {
const response = await transport.post('/createInvoice', params)
return (response as { invoiceLink: string }).invoiceLink
} catch (e) {
return null
}
} | /**
* Create a new invoice
*
* @param params - Params for creating a new invoice
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/domain/services/useInvoice.ts#L114-L122 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | toPrice | function toPrice(usdAmount: number): number {
return Math.round(usdAmount * 100)
} | /**
* Convert USD amount to price in cents
*
* @param usdAmount - USD amount
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/domain/services/useInvoice.ts#L129-L131 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | setStartDate | function setStartDate(date: TripDetails['startDate']): void {
trip.startDate = date
} | /**
* Selects the start date of the trip
*
* @param date - The date of the trip
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/domain/services/useTripDetails.ts#L92-L94 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | setEndDate | function setEndDate(date: TripDetails['endDate']): void {
trip.endDate = date
} | /**
* Selects the end date of the trip
*
* @param date - The end date of the trip
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/domain/services/useTripDetails.ts#L101-L103 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | setCity | function setCity(cityId: TripDetails['city']): void {
trip.city = cityId
} | /**
* Selects the location of the trip
*
* @param cityId - The location of the trip
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/domain/services/useTripDetails.ts#L110-L112 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | setHotel | function setHotel(hotel: TripDetails['hotel']): void {
trip.hotel = hotel
} | /**
* Selects the hotel of the trip
*
* @param hotel - The hotel of the trip
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/domain/services/useTripDetails.ts#L119-L121 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | setRoom | function setRoom(room: TripDetails['room']): void {
trip.room = room
} | /**
* Selects the room of the trip
*
* @param room - The room of the trip
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/domain/services/useTripDetails.ts#L128-L130 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | selectDefault | function selectDefault(): void {
const today = new Date()
const tomorrow = new Date(today)
tomorrow.setDate(tomorrow.getDate() + 1)
setStartDate(today)
setEndDate(tomorrow)
if (cities.value.length > 0) {
setCity(cities.value[0].id)
}
} | /**
* Selects default trip details:
* - current date as start date
* - current date + 1 day as end date
* - first location as location
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/domain/services/useTripDetails.ts#L153-L165 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | addThumb | function addThumb<T extends { picture: string }>(entity: T): T & { pictureThumb: string } {
const pictureName = entity.picture.split('/').pop() as keyof typeof Thumbnails.thumbs
return {
...entity,
pictureThumb: Thumbnails.thumbs[pictureName],
}
} | /**
* Add picture thumb to an entity based on the picture name
*
* @param entity - something with "picture" property
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/infra/store/hotels/mock/hotels.ts#L313-L320 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | addThumbs | function addThumbs(hotels: Hotel[]): Hotel[] {
return hotels.map((hotel) => {
/**
* Add picture thumb to rooms as well
*/
hotel.rooms = hotel.rooms.map(addThumb)
return addThumb(hotel)
})
} | /**
* Add picture thumbs to hotels based on the picture name
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/infra/store/hotels/mock/hotels.ts#L325-L334 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | ImageCache.constructor | constructor(private readonly maxSize = 100) {} | /**
* @param maxSize — Max size of the cache. If cache is full, first element will be removed
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/infra/store/thumbs/image.cache.ts#L14-L14 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | ImageCache.get | public get(url: string): string | undefined {
return this.cache.get(url)
} | /**
* Get image data from cache
* @param url image url
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/infra/store/thumbs/image.cache.ts#L20-L22 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | ImageCache.set | public set(url: string, data: string): void {
/**
* Check if image already exists in cache
*/
if (this.cache.has(url)) {
return
}
/**
* If cache is full, remove first element
*/
if (this.cache.size >= this.maxSize) {
const firstKey = this.cache.keys().next().value
this.cache.delete(firstKey)
}
/**
* Add new image data to cache
*/
this.cache.set(url, data)
} | /**
* Set image data in cache
* @param url image url
* @param data image data
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/infra/store/thumbs/image.cache.ts#L29-L50 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | ApiTransport.constructor | constructor(baseUrl: string) {
super(baseUrl, {
/**
* Method for creating an Error based on API response
*
* @param status - HTTP status
* @param payload - Response JSON payload
* @param endpoint - API endpoint we requested
*/
errorFormatter(status, payload) {
const { message, code } = (payload as ApiErrorResponse)
let errorText = ''
/**
* If 'code' is provided, use it as an error text so we can show it to the user using corresponded i18n message
*/
if (code !== undefined) {
errorText = code.toString()
} else if (message !== undefined) {
errorText = message
} else {
errorText = 'Unknown error'
}
/**
* Create error based on response status
*/
switch (status) {
case 401:
case 403:
return new UnauthorizedError(errorText)
case 404:
return new NotFoundError(errorText)
default:
return new Error(errorText)
}
},
})
} | /**
* Constructor for api transport
*
* @param baseUrl - Base URL
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/infra/transport/api/index.ts#L16-L55 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | ApiTransport.get | public async get<Payload>(endpoint: string, data?: any): Promise<Payload> {
const response = await super.get(endpoint, data)
return response as Payload
} | /**
* Make GET request to the API
*
* @param endpoint - API endpoint
* @param data - data to be sent url encoded
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/infra/transport/api/index.ts#L63-L67 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | ApiTransport.post | public async post<Payload>(endpoint: string, data?: any): Promise<Payload> {
const response = await super.post(endpoint, data)
return response as Payload
} | /**
* Make POST request to theAPI
*
* @param endpoint - API endpoint
* @param data - data to be sent with request body
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/infra/transport/api/index.ts#L75-L79 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | FetchTransport.constructor | constructor(private readonly baseUrl: string, private readonly options?: FetchTransportOptions) {
} | /**
* Fetch constructor
*
* @param baseUrl - Base URL
* @param options - Transport options
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/infra/transport/fetch/index.ts#L29-L30 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | FetchTransport.get | public async get(endpoint: string, data?: JSONValue): Promise<JSONValue> {
const resourceUrl = new URL(this.baseUrl + endpoint)
if (data !== undefined) {
resourceUrl.search = new URLSearchParams(data as Record<string, string>).toString()
}
const response = await fetch(resourceUrl.toString(), {
method: 'GET',
headers: this.headers,
})
return await this.parseResponse(response, endpoint)
} | /**
* Gets specific resource
*
* @template Response - Response data type
* @param endpoint - API endpoint
* @param data - data to be sent url encoded
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/infra/transport/fetch/index.ts#L39-L52 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | FetchTransport.post | public async post(endpoint: string, payload?: JSONValue): Promise<JSONValue> {
this.headers.set('Content-Type', 'application/json')
/**
* Send payload as body to allow Fastify accept it
*/
const response = await fetch(this.baseUrl + endpoint, {
method: 'POST',
headers: this.headers,
body: payload !== undefined ? JSON.stringify(payload) : undefined,
})
return await this.parseResponse(response, endpoint)
} | /**
* Make POST request to update some resource
*
* @template Response - Response data type
* @param endpoint - API endpoint
* @param payload - JSON POST data body
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/infra/transport/fetch/index.ts#L61-L74 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | FetchTransport.parseResponse | private async parseResponse(response: Response, endpoint: string): Promise<JSONValue> {
let payload
/**
* Try to parse error data. If it is not valid JSON, throw error
*/
try {
payload = await response.json()
} catch (error) {
throw new Error(`The response is not valid JSON (requesting ${endpoint})`)
}
/**
* The 'ok' read-only property of the Response interface contains a Boolean
* stating whether the response was successful (status in the range 200-299) or not
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/Response/ok
*/
if (response.ok) {
return payload
}
/**
* If error formatter is provided, use it to create an Error based on status and payload
*/
if (this.options?.errorFormatter !== undefined) {
throw this.options.errorFormatter(response.status, payload, endpoint)
} else {
throw new Error(`${response.statusText || 'Bad response'} (requesting ${endpoint}))`)
}
} | /**
* Check response for errors
*
* @param response - Response object
* @param endpoint - API endpoint used for logging
* @throws Error
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/client/src/infra/transport/fetch/index.ts#L83-L113 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | Bot.constructor | constructor(private readonly config: typeof Config) {} | /**
* @param config - Config instance
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/server/src/api/bot.ts#L16-L16 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | Bot.run | public async run(): Promise<TelegramBot> {
this.bot = new TelegramBot(this.config.botToken, {
// @ts-ignore — undocumented option
testEnvironment: this.config.isTestEnvironment,
})
console.log(`🤖 Bot is running...`);
/**
* Check if webhook is set
* If not — set it
*/
try {
const whInfo = await this.bot.getWebHookInfo()
if ('url' in whInfo && whInfo.url !== '') {
console.log('🤖 WebHook info: ', whInfo);
} else {
await this.setWebhook();
}
} catch (e) {
console.log('getWebHookInfo error', e);
}
/**
* Listen for messages from Telegram
*/
this.bot.on('message', (msg) => {
this.onMessage(msg);
})
/**
* Listen for pre_checkout_query event
*/
this.bot.on('pre_checkout_query', (update) => {
this.preCheckoutQuery(update);
})
return this.bot;
} | /**
* Listen for messages from Telegram
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/server/src/api/bot.ts#L21-L60 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | Bot.onMessage | private async onMessage(msg: TelegramBot.Message): Promise<void> {
const chatId = msg.chat.id
console.log('📥', msg);
switch (msg.text) {
case '/start':
await this.replyStartMessage(chatId)
return
case '/help':
await this.replyHelpMessage(chatId)
return
}
if (msg.successful_payment) {
console.log('💰 successful_payment', msg.successful_payment);
await this.bot!.sendMessage(chatId, '*Your order was accepted! Have a nice trip! 🎉* \n\nIt is not a real payment, so you\'re not charged. The hotel exists only in our imagination. Thanks for testing! \n\nDiscover the source code and documentation: \nhttps://github.com/neSpecc/telebook', {
parse_mode: 'Markdown',
reply_markup: {
inline_keyboard: [
[{
text: `🦄 Open ${this.config.appName}`,
web_app: {
url: this.config.webAppUrl,
},
}],
],
}
})
return;
}
/**
* Send message with inline query containing a link to the mini-app
*/
this.sendAppButton(chatId)
} | /**
* Handler for messages from Telegram
*
* @param msg - object that the bot got from Telegram
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/server/src/api/bot.ts#L67-L105 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | Bot.replyStartMessage | private async replyStartMessage(chatId: number): Promise<void> {
await this.bot!.sendMessage(chatId, 'Welcome to the hotel booking bot! Hope you enjoy the application I have 🏨', {
reply_markup: {
inline_keyboard: [
[{
text: `🦄 Open ${this.config.appName}`,
web_app: {
url: this.config.webAppUrl,
},
}],
],
}
});
} | /**
* Reply to the /start command
*
* @param chatId - chat id to send message to
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/server/src/api/bot.ts#L112-L125 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | Bot.replyHelpMessage | private async replyHelpMessage(chatId: number): Promise<void> {
await this.bot!.sendMessage(chatId, 'Actually I\'m just an example bot, so all I can do is to send you a link to the mini-app 🤖', {
reply_markup: {
inline_keyboard: [
[{
text: `🦄 Open ${this.config.appName}`,
web_app: {
url: this.config.webAppUrl,
},
}],
],
}
});
} | /**
* Reply to the /help command
*
* @param chatId - chat id to send message to
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/server/src/api/bot.ts#L132-L145 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | Bot.sendAppButton | private async sendAppButton(chatId: number): Promise<void> {
await this.bot!.sendMessage(chatId, 'Click the button below to launch an app', {
reply_markup: {
inline_keyboard: [
[{
text: `🦄 Open ${this.config.appName}`,
web_app: {
url: this.config.webAppUrl,
},
}],
],
},
})
} | /**
* Send message with inline query containing a link to the mini-app
*
* @param chatId - chat id to send message to
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/server/src/api/bot.ts#L152-L165 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | Bot.preCheckoutQuery | private preCheckoutQuery(update: TelegramBot.PreCheckoutQuery): void {
console.log('🤖 pre_checkout_query: ', update);
/**
* @todo validate order here: get order from database and compare with update
*/
this.bot!.answerPreCheckoutQuery(update.id, true)
} | /**
* Handler for pre_checkout_query event
*
* Got when user clicks on "Pay" button
* We need to validate order here and answer with answerPreCheckoutQuery() in 10sec
*
* @see https://core.telegram.org/bots/payments#7-pre-checkout
*
* @param update - object that the bot got from Telegram
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/server/src/api/bot.ts#L178-L186 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | Bot.setWebhook | private async setWebhook(): Promise<void> {
try {
console.log('🤖 setting a webhook to @BotFather: ', `${this.config.publicHost}/bot`);
const setHookResponse = await this.bot!.setWebHook(`${this.config.publicHost}/bot`);
if (setHookResponse === true){
console.log('🤖 webhook set ᕕ( ᐛ )ᕗ');
} else {
console.warn('🤖 webhook not set (╯°□°)╯︵ ┻━┻');
console.warn('setHookResponse', setHookResponse);
}
} catch (e) {
console.warn('Can not set Telegram Webhook')
console.warn(e)
}
} | /**
* Set webhook for Telegram bot
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/server/src/api/bot.ts#L191-L207 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | Bot.sendMessageQueue | private async sendMessageQueue(chatId: TelegramBot.ChatId, messages: {text: string, options?: TelegramBot.SendMessageOptions}[]): Promise<void> {
messages.forEach((message, index) => {
setTimeout(async () => {
await this.bot!.sendMessage(chatId, message.text, message.options)
}, index * 500);
})
} | /**
* To send several messages at once we need to add a small timeout between them
*
* @param chatId - chat id to send message to
* @param messages - array of messages to send
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/server/src/api/bot.ts#L215-L221 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | HttpApi.constructor | constructor(private readonly config: typeof Config, private readonly bot: TelegramBot) {} | /**
* Constructor
*
* @param config - Config instance
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/server/src/api/http.ts#L23-L23 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | HttpApi.ready | public async ready(): Promise<void> {
return this.server.ready()
} | /**
* Method used to know when the fastify instance is ready
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/server/src/api/http.ts#L28-L30 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | HttpApi.run | public async run(): Promise<void> {
this.server.register(Router, {
config: this.config,
bot: this.bot,
})
this.server.register(fastifyStatic, {
root: path.join(__dirname, '../../public'),
});
this.server.setErrorHandler((error, request, reply) => {
console.error(error)
reply.status(500).send({
error: 'Internal Server Error',
})
})
/**
* In test environment we listen for requests as usual
* In production we don't listen for requests, because we use serverless deployment
*/
if (this.config.isTestEnvironment) {
this.listen()
}
/**
* Allow cors for allowed origins from config
*/
await this.server.register(cors, {
origin: this.config.allowedOrigins,
});
} | /**
* Run HTTP server
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/server/src/api/http.ts#L35-L67 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | HttpApi.listen | private listen(): void {
this.server.listen({
port: parseInt(this.config.port),
}, (err: Error | null, address: string) => {
if (err) {
console.error(err)
process.exit(1)
}
console.log(`🫡 ${this.config.appName || 'Server'} API listening at ${address}`)
})
} | /**
* Listen for requests
*
* Used only in test environment
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/server/src/api/http.ts#L74-L84 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | HttpApi.emit | emit(request: any, response: any): void {
this.server.server.emit('request', request, response)
} | /**
* Emit request to the server
* Used only in serverless environment
*
* @param request - Request object
* @param response - Response object
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/server/src/api/http.ts#L93-L95 | 02af111d7c9b128abb958de07a9a68de4d249406 |
telebook | github_2023 | neSpecc | typescript | _notify | function _notify(text: string): void {
/**
* Send curl -X POST https://notify.bot.ifmo.su/u/ABCD1234 -d "message=Hello world"
*/
const url = process.env.NOTIFY_WEBHOOK
if (!url) {
console.info('Notify webhook is not set')
console.info('💌 ' + text)
return
}
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: `message=${text}&parse_mode=Markdown`
}
fetch(url, options).then(response => response.text()).then((response) => {
console.info('💌 Sent', response)
}).catch((error) => {
console.error('💌 ❌ Sending failed', error)
})
} | /**
* Send a message to telegram
*
* @param text The text to send
*/ | https://github.com/neSpecc/telebook/blob/02af111d7c9b128abb958de07a9a68de4d249406/server/src/infra/utils/notify/notify.ts#L18-L43 | 02af111d7c9b128abb958de07a9a68de4d249406 |
dolt-workbench | github_2023 | dolthub | typescript | ConnectionProvider.mysqlConnection | async mysqlConnection(): Promise<mysql.Connection> {
const { workbenchConfig } = this;
if (!workbenchConfig) {
throw new Error("Workbench config not found for MySQL connection");
}
const options: mysql.ConnectionOptions = {
uri: workbenchConfig.connectionUrl,
ssl: workbenchConfig.useSSL
? {
rejectUnauthorized: false,
}
: undefined,
connectionLimit: 1,
dateStrings: ["DATE"],
// Allows file upload via LOAD DATA
flags: ["+LOCAL_FILES"],
};
return mysql.createConnection(options);
} | // Used for file upload only, must destroy after using | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/graphql-server/src/connections/connection.provider.ts#L40-L61 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | FileStoreService.getStore | getStore(): DatabaseConnection[] {
if (!fs.existsSync(storePath)) {
return [];
}
try {
const file = fs.readFileSync(storePath, {
encoding: "utf8",
});
if (!file) {
return [];
}
const parsed = JSON.parse(file);
return parsed;
} catch (err) {
console.error("Error reading store.json:", err);
return [];
}
} | // eslint-disable-next-line class-methods-use-this | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/graphql-server/src/fileStore/fileStore.service.ts#L14-L31 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | DoltQueryFactory.getTableInfo | async getTableInfo(args: t.TableArgs): Promise<TableDetails | undefined> {
return this.queryMultiple(
async query => getTableInfoWithQR(query, args),
args.databaseName,
args.refName,
);
} | // TODO: Why does qr.getTable() not work for foreign keys for Dolt? | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/graphql-server/src/queryFactory/dolt/index.ts#L55-L61 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | getOrderByFromCols | function getOrderByFromCols(numCols: number): string {
if (!numCols) return "";
const pkCols = Array.from({ length: numCols })
.map(() => `? ASC`)
.join(", ");
return pkCols === "" ? "" : `ORDER BY ${pkCols} `;
} | // Creates ORDER BY statement with column parameters | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/graphql-server/src/queryFactory/dolt/queries.ts#L105-L111 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | DoltgresQueryFactory.getTableInfo | async getTableInfo(
args: t.TableMaybeSchemaArgs,
): Promise<TableDetails | undefined> {
return this.queryQR(
async qr => getTableInfoWithQR(qr, args),
args.databaseName,
args.refName,
);
} | // TODO: qr.getTable() does not allow specifying a database for doltgres | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/graphql-server/src/queryFactory/doltgres/index.ts#L66-L74 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | getOrderByFromCols | function getOrderByFromCols(cols: string[]): string {
if (!cols.length) return "";
const pkCols = cols.map(col => `${col} ASC`).join(", ");
return pkCols === "" ? "" : `ORDER BY ${pkCols} `;
} | // Creates ORDER BY statement with column parameters | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/graphql-server/src/queryFactory/doltgres/queries.ts#L114-L118 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | MySQLQueryFactory.getBranch | async getBranch(args: t.BranchArgs): t.USPR {
return {
name: args.branchName,
latest_commit_date: new Date(),
latest_committer: "",
head: "",
};
} | // Returns static branch | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/graphql-server/src/queryFactory/mysql/index.ts#L201-L208 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | PostgresQueryFactory.checkoutDatabase | async checkoutDatabase(qr: QueryRunner, dbName: string): Promise<void> {
const currentDb = await qr.getCurrentDatabase();
if (dbName !== currentDb) {
throw new Error("Databases do not match");
}
} | // eslint-disable-next-line class-methods-use-this | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/graphql-server/src/queryFactory/postgres/index.ts#L59-L64 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | PostgresQueryFactory.getSqlSelect | async getSqlSelect(
args: t.RefMaybeSchemaArgs & { queryString: string },
): Promise<{ rows: t.RawRows; warnings?: string[] }> {
return this.queryQR(
async qr => {
if (args.schemaName) {
await changeSchema(qr, args.schemaName);
}
return qr.query(args.queryString, []);
},
args.databaseName,
args.refName,
);
} | // TODO: get warnings for postgres | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/graphql-server/src/queryFactory/postgres/index.ts#L138-L151 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | TableResolver.maybeTable | async maybeTable(
@Args() args: TableMaybeSchemaArgs,
): Promise<Table | undefined> {
return handleTableNotFound(async () => this.table(args));
} | // Utils | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/graphql-server/src/tables/table.resolver.ts#L43-L47 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | renderModal | function renderModal() {
const { user } = setup(
<MockedProvider mocks={[mocks.deleteBranchMutationMock]}>
<DeleteModal
asset="object"
isOpen
setIsOpen={(_: boolean) => {}}
mutationProps={{
hook: useDeleteBranchMutation,
variables: mocks.branchParams,
}}
>
{mocks.deleteMessage}
</DeleteModal>
</MockedProvider>,
);
return { user };
} | // This test uses a real mutation that is mocked. It was too difficult to mock the mutation hook directly using jest. | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/web/renderer/components/DeleteModal/index.test.tsx#L14-L31 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | setFilter | const setFilter = async (rowType: Maybe<DiffRowType>) => {
setState({ filter: rowType });
const setRowDiffs = (rd: RowDiffForTableListFragment[]) =>
setState({ rowDiffs: rd });
await handleQuery(setRowDiffs, 0, rowType ?? DiffRowType.All);
}; | // Changes diff row filter, starts with first page diffs | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/web/renderer/components/DiffTable/DataDiff/useRowDiffs.ts#L77-L82 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | getTitle | function getTitle(doltDocsQueryDocName?: string, docName?: string): string {
if (docName) return docName;
if (doltDocsQueryDocName) return doltDocsQueryDocName;
return "There is no doc to display.";
} | // Prioritize docName url param if it exists | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/web/renderer/components/DocMarkdown/Title.tsx#L32-L36 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | calculatePosition | function calculatePosition(
graph: Graph,
startPosition: number,
nodes: Array<Node<NodeData>>,
visited: VisitedMask,
): CalculatePositionReturnType {
const graphCopy = graph;
let endPos = startPosition;
const nodesCopy = [...nodes];
const visitedCopy = visited;
let stack = findStartNodes(graphCopy, visitedCopy);
if (stack.length && graphCopy[stack[0]].sourceCount === 0) {
stack.forEach(s => {
if (!visited[s]) {
nodesCopy.forEach(n => {
if (n.id === s) {
// eslint-disable-next-line no-param-reassign
n.position = { x: endPos, y: 0 };
endPos += (n.width ?? 300) + 200;
}
});
visitedCopy[s] = 1;
delete graphCopy[s];
}
});
return {
graph: graphCopy,
count: endPos,
nodes: nodesCopy,
visited: visitedCopy,
};
}
while (stack.length) {
let newStack: string[] = [];
let startY = 0;
let largestW = 0;
// eslint-disable-next-line @typescript-eslint/no-loop-func
stack.forEach((s, i) => {
if (!visited[s]) {
nodesCopy.forEach(n => {
if (n.id === s) {
// eslint-disable-next-line no-param-reassign
n.position = { x: endPos + i * 100, y: startY };
const w = endPos + i * 100 + (n.width || 300);
largestW = largestW < w ? w : largestW;
startY += Math.ceil(n.data.columns.length / 5) * 200;
}
});
visitedCopy[s] = 1;
const sortedTarget = Array.from(graphCopy[s].target).sort(
(a, b) =>
graphCopy[s].targetIndexCount[a] - graphCopy[s].targetIndexCount[b],
);
newStack = [...newStack, ...sortedTarget];
delete graphCopy[s];
}
});
endPos = largestW + 300;
stack = newStack;
}
return {
graph: graphCopy,
count: endPos,
nodes: nodesCopy,
visited: visitedCopy,
};
} | // use breadth first search to find groups of connected tables, and reassign the position of each node | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/web/renderer/components/SchemaDiagram/utils.ts#L163-L234 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | parseUseQuery | function parseUseQuery(q: string): RevisionInfo {
const lower = q.toLowerCase();
const split = q.split(" ");
const rev = split[1];
if (!lower.includes("`")) {
return { databaseName: rev, branchName: undefined };
}
const removedTicks = rev.split("`")[1];
if (!lower.includes("/")) {
return { databaseName: removedTicks, branchName: undefined };
}
const [databaseName, ...branchNameParts] = removedTicks.split("/");
return { databaseName, branchName: branchNameParts.join("/") };
} | // Parse string "use `<databaseName>/<branchName>`" into { databaseName: <databaseName>, branchName: <branchName> } | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/web/renderer/components/SqlDataTable/SqlMessage/utils.ts#L23-L36 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | parseDoltCheckoutQuery | function parseDoltCheckoutQuery(q: string): RevisionInfo {
const lower = q.toLowerCase();
const split = lower.split(/'|"/);
const branchName = split[1];
if (branchName === "-b") return { branchName: split[3] };
return { branchName };
} | // Parse string "dolt_checkout('<branchName>')"|"dolt_checkout('-b', '<branchName>')" into { branchName: <branchName> } | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/web/renderer/components/SqlDataTable/SqlMessage/utils.ts#L39-L45 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | Inner | function Inner(props: InnerProps) {
const router = useRouter();
const res = useCurrentDatabaseQuery();
if (res.loading) {
return <Loader loaded={false} />;
}
if (
res.error &&
(errorMatches(gqlDatabaseNotFoundErr, res.error) ||
errorMatches("Data source service not initialized", res.error))
) {
router.push("/").catch(console.error);
return <Loader loaded={false} />;
}
return props.children;
} | // eslint-disable-next-line @typescript-eslint/promise-function-async | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/web/renderer/components/layouts/DatabaseLayout/Wrapper.tsx#L23-L38 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | getRequest | const getRequest = (params: DatabaseParams) => {
return {
query: TagListDocument,
variables: params,
};
}; | // export const writePermRepoRoleMock = repoRoleMock(databaseParams, RepoRole.Writer); | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/web/renderer/components/pageComponents/DatabasePage/ForReleases/ReleaseList/mocks.ts#L57-L62 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | refetch | const refetch = async () => {
try {
const newRes = await res.refetch(params);
setTags(newRes.data.tags.list);
} catch (e) {
handleCaughtApolloError(e, setErr);
}
}; | // const [pageToken, setPageToken] = useState(data?.commits.nextPageToken); | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/web/renderer/components/pageComponents/DatabasePage/ForReleases/ReleaseList/useTagList.ts#L27-L34 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | getIntMultiplier | function getIntMultiplier(type: string): number {
const lower = type.toLowerCase();
if (lower.startsWith("big")) {
return 2 ** 62;
}
if (lower.startsWith("medium")) {
return 8388607;
}
if (lower.startsWith("small")) {
return 32767;
}
if (lower.startsWith("tiny")) {
return 127;
}
return 2147483647;
} | // Uses max value signed https://dev.mysql.com/doc/refman/8.0/en/integer-types.html | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/web/renderer/components/pageComponents/DatabasePage/ForTable/utils.ts#L54-L69 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | getRandomNumFromRange | function getRandomNumFromRange(min: number, max: number): number {
const nmin = Math.ceil(min);
const nmax = Math.floor(max);
return Math.floor(Math.random() * (nmax - nmin + 1) + nmin);
} | // Inclusive | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/web/renderer/components/pageComponents/DatabasePage/ForTable/utils.ts#L122-L126 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | addEmptyRowsForPastedRows | function addEmptyRowsForPastedRows(
pastedRows: string[][],
rowIdx: number,
cols: Columns,
): Row[] {
if (pastedRows.length === 0) return state.rows;
const numMoreRows = pastedRows.length - (state.rows.length - rowIdx);
if (numMoreRows <= 0) return state.rows;
const next = nextId;
const newRows = nTimesWithIndex(numMoreRows, n => {
setNextId();
return getRow(next + n, n + state.rows.length, cols);
});
return [...state.rows, ...newRows];
} | // If pasted rows go beyond row boundary, add more empty rows | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/web/renderer/components/pageComponents/FileUploadPage/Steps/Upload/EditableTable/TableGrid/useGrid.ts#L117-L131 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | getEmptyRows | function getEmptyRows(cols: Columns, numRows: number): Row[] {
const rows = [];
for (let i = 0; i < numRows; i++) {
rows.push(getRow(i, i, cols));
}
return rows;
} | // GET ROWS | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/web/renderer/components/pageComponents/FileUploadPage/Steps/Upload/EditableTable/TableGrid/utils.ts#L162-L168 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.