(
value: any,
maxDocumentLength: number,
options: EJSONOptions = {}
)
| 472 | | Binary; |
| 473 | /** @internal */ |
| 474 | export function stringifyWithMaxLen( |
| 475 | value: any, |
| 476 | maxDocumentLength: number, |
| 477 | options: EJSONOptions = {} |
| 478 | ): string { |
| 479 | let strToTruncate = ''; |
| 480 | |
| 481 | let currentLength = 0; |
| 482 | const maxDocumentLengthEnsurer = function maxDocumentLengthEnsurer(key: string, value: any) { |
| 483 | if (currentLength >= maxDocumentLength) { |
| 484 | return undefined; |
| 485 | } |
| 486 | // Account for root document |
| 487 | if (key === '') { |
| 488 | // Account for starting brace |
| 489 | currentLength += 1; |
| 490 | return value; |
| 491 | } |
| 492 | |
| 493 | // +4 accounts for 2 quotation marks, colon and comma after value |
| 494 | // Note that this potentially undercounts since it does not account for escape sequences which |
| 495 | // will have an additional backslash added to them once passed through JSON.stringify. |
| 496 | currentLength += key.length + 4; |
| 497 | |
| 498 | if (value == null) return value; |
| 499 | |
| 500 | switch (typeof value) { |
| 501 | case 'string': |
| 502 | // +2 accounts for quotes |
| 503 | // Note that this potentially undercounts similarly to the key length calculation |
| 504 | currentLength += value.length + 2; |
| 505 | break; |
| 506 | case 'number': |
| 507 | case 'bigint': |
| 508 | currentLength += String(value).length; |
| 509 | break; |
| 510 | case 'boolean': |
| 511 | currentLength += value ? 4 : 5; |
| 512 | break; |
| 513 | case 'object': |
| 514 | if (isUint8Array(value)) { |
| 515 | // '{"$binary":{"base64":"<base64 string>","subType":"XX"}}' |
| 516 | // This is an estimate based on the fact that the base64 is approximately 1.33x the length of |
| 517 | // the actual binary sequence https://en.wikipedia.org/wiki/Base64 |
| 518 | currentLength += (22 + value.byteLength + value.byteLength * 0.33 + 18) | 0; |
| 519 | } else if ('_bsontype' in value) { |
| 520 | const v = value as BSONObject; |
| 521 | switch (v._bsontype) { |
| 522 | case 'Int32': |
| 523 | currentLength += String(v.value).length; |
| 524 | break; |
| 525 | case 'Double': |
| 526 | // Account for representing integers as <value>.0 |
| 527 | currentLength += |
| 528 | (v.value | 0) === v.value ? String(v.value).length + 2 : String(v.value).length; |
| 529 | break; |
| 530 | case 'Long': |
| 531 | currentLength += v.toString().length; |
no outgoing calls
no test coverage detected