UNPKG

4nm

Version:

TypeScript reimplementation of Telegram's official library for communicating with Telegram Web Apps.

90 lines (89 loc) 3.21 kB
import { toRGBExt } from '../colors'; export function createJSONStructParser(schema, optional) { return value => { if (value === null || value === undefined) { if (optional) { return; } throw new TypeError(`Unable to parse value as JSON as it is empty (null or undefined).`); } let json = value; // Convert value to JSON in case, it is string. We expect value to be // JSON string. if (typeof json === 'string') { try { json = JSON.parse(json); } catch (e) { throw new SyntaxError(`Unable to parse value "${value}" as JSON as long as value is not JSON string.`); } } // We expect json to usual object. if (typeof json !== 'object' || json === null || Array.isArray(json)) { throw new TypeError(`Unable to value "${value}" as JSON as long as value is not JSON object.`); } // Iterate over each schema property and extract it from JSON. const result = {}; for (const prop in schema) { const [paramName, parser] = schema[prop]; try { const value = parser(json[paramName]); if (value !== undefined) { result[prop] = value; } } catch (e) { throw new Error(`Unable to parse parameter "${paramName}"`, { cause: e }); } } return result; }; } /** * Converts value received from some JSON to string. * @param value - raw value. * @throws {TypeError} Value has incorrect type. */ export const parseJSONParamAsInt = value => { if (typeof value !== 'number') { throw new TypeError(`Unable to value "${value}" as int`); } return value; }; /** * Converts value received from some JSON to string. * @param value - raw value. * @throws {TypeError} Value has incorrect type. */ export const parseJSONParamAsString = value => { if (typeof value !== 'string') { throw new TypeError(`Unable to value "${value}" as string`); } return value; }; /** * Converts value received from some JSON to string or undefined. * @param value - raw value. * @throws {TypeError} Value has incorrect type. */ export const parseJSONParamAsOptString = value => value === undefined ? value : parseJSONParamAsString(value); /** * Converts value received from some JSON to RGB in full format or undefined. * @param value - raw value. * @throws {TypeError} Value has incorrect type. */ export const parseJSONParamAsOptRGBExt = value => value === undefined ? value : toRGBExt(parseJSONParamAsString(value)); /** * Converts value received from some JSON to boolean or undefined. * @param value - raw value. * @throws {TypeError} Value has incorrect type. */ export const parseJSONParamAsOptBool = value => { if (value === undefined) { return; } if (typeof value !== 'boolean') { throw new TypeError(`Unable to value "${value}" as boolean`); } return value; };