From 55edbde3e79e7cf82598762bdf5f141fc5589229 Mon Sep 17 00:00:00 2001 From: Alina Sireneva Date: Thu, 7 Sep 2023 22:26:52 +0300 Subject: [PATCH] fix: fixed new error codegen --- packages/tl-utils/src/codegen/errors.ts | 35 +++++++++++-------------- 1 file changed, 16 insertions(+), 19 deletions(-) diff --git a/packages/tl-utils/src/codegen/errors.ts b/packages/tl-utils/src/codegen/errors.ts index f78d1ea7..44190950 100644 --- a/packages/tl-utils/src/codegen/errors.ts +++ b/packages/tl-utils/src/codegen/errors.ts @@ -2,18 +2,16 @@ import { TlErrors } from '../types' import { snakeToCamel } from './utils' const TEMPLATE_JS = ` -const _descriptionsMap = { -{descriptionsMap} -} +const _descriptionsMap = JSON.parse('{descriptionsMap}') class RpcError extends Error { - constructor(code, name) { - super(_descriptionsMap[name] || 'Unknown RPC error: [' + code + ':' + name + ']'); + constructor(code, text) { + super(_descriptionsMap[text] || 'Unknown RPC error: [' + code + ':' + text + ']'); this.code = code; - this.name = name; + this.text = text; } - static is(err, name) { return err.constructor === RpcError && (!name || err.name === name); } - is(name) { return this.name === name; } + static is(err, text) { return err.constructor === RpcError && (!text || err.text === text); } + is(text) { return this.text === text; } } RpcError.fromTl = function (obj) { const err = new RpcError(obj.errorCode, obj.errorMessage); @@ -109,7 +107,7 @@ export function generateCodeForErrors( errors: TlErrors, exports = 'exports.', ): [string, string] { - let descriptionsMap = '' + const descriptionsMap: Record = {} let texts = '' let argMap = '' let matchers = '' @@ -125,9 +123,7 @@ export function generateCodeForErrors( const [name, placeholders] = parseCode(error.name, error._paramNames) if (error.description) { - descriptionsMap += ` '${name}': ${JSON.stringify( - error.description, - )},\n` + descriptionsMap[name] = error.description } texts += ` | '${name}'\n` @@ -142,12 +138,10 @@ export function generateCodeForErrors( ' },\n' const regex = name.replace('%d', '(\\d+)') - const setters = placeholders.map( - (it, i) => `err.${it} = parseInt(match[${i + 1}])`, - ) - const settersStr = - setters.length > 1 ? `{ ${setters.join('; ')} }` : setters[0] - matchers += ` if ((match=obj.errorMessage.match(/^${regex}$/))!=null)${settersStr}\n` + const setters = placeholders + .map((it, i) => `err.${it} = parseInt(match[${i + 1}])`) + .join('; ') + matchers += ` if ((match=obj.errorMessage.match(/^${regex}$/))!=null){ err.text = '${name}'; ${setters} }\n` } } @@ -156,7 +150,10 @@ export function generateCodeForErrors( template(TEMPLATE_JS, { exports, statics: staticsJs, - descriptionsMap, + descriptionsMap: JSON.stringify(descriptionsMap).replace( + /'/g, + "\\'", + ), matchers, }), ]