parser_cache.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. 'use strict';
  2. const { createLRU } = require('lru.min');
  3. const parserCache = createLRU({
  4. max: 15000,
  5. });
  6. function keyFromFields(type, fields, options, config) {
  7. const res = [
  8. type,
  9. typeof options.nestTables,
  10. options.nestTables,
  11. Boolean(options.rowsAsArray),
  12. Boolean(options.supportBigNumbers || config.supportBigNumbers),
  13. Boolean(options.bigNumberStrings || config.bigNumberStrings),
  14. typeof options.typeCast === 'boolean'
  15. ? options.typeCast
  16. : typeof options.typeCast,
  17. options.timezone || config.timezone,
  18. Boolean(options.decimalNumbers),
  19. options.dateStrings,
  20. ];
  21. for (let i = 0; i < fields.length; ++i) {
  22. const field = fields[i];
  23. res.push([
  24. field.name,
  25. field.columnType,
  26. field.length,
  27. field.schema,
  28. field.table,
  29. field.flags,
  30. field.characterSet,
  31. ]);
  32. }
  33. return JSON.stringify(res, null, 0);
  34. }
  35. function getParser(type, fields, options, config, compiler) {
  36. const key = keyFromFields(type, fields, options, config);
  37. let parser = parserCache.get(key);
  38. if (parser) {
  39. return parser;
  40. }
  41. parser = compiler(fields, options, config);
  42. parserCache.set(key, parser);
  43. return parser;
  44. }
  45. function setMaxCache(max) {
  46. parserCache.resize(max);
  47. }
  48. function clearCache() {
  49. parserCache.clear();
  50. }
  51. module.exports = {
  52. getParser: getParser,
  53. setMaxCache: setMaxCache,
  54. clearCache: clearCache,
  55. _keyFromFields: keyFromFields,
  56. };