FlagParam.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * Copyright (C) 2024 Puter Technologies Inc.
  3. *
  4. * This file is part of Puter.
  5. *
  6. * Puter is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License as published
  8. * by the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU Affero General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Affero General Public License
  17. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. */
  19. const APIError = require('../../api/APIError');
  20. module.exports = class FlagParam {
  21. constructor (srckey, options) {
  22. this.srckey = srckey;
  23. this.options = options ?? {};
  24. this.optional = this.options.optional ?? false;
  25. this.default = this.options.default ?? false;
  26. }
  27. async consolidate ({ req, getParam }) {
  28. const log = globalThis.services.get('log-service').create('flag-param');
  29. const value = getParam(this.srckey);
  30. if ( value === undefined || value === '' ) {
  31. if ( this.optional ) return this.default;
  32. throw APIError.create('field_missing', null, {
  33. key: this.srckey,
  34. });
  35. }
  36. if ( typeof value === 'string' ) {
  37. if (
  38. value === 'true' || value === '1' || value === 'yes'
  39. ) return true;
  40. if (
  41. value === 'false' || value === '0' || value === 'no'
  42. ) return false;
  43. throw APIError.create('field_invalid', null, {
  44. key: this.srckey,
  45. expected: 'boolean',
  46. });
  47. }
  48. if ( typeof value === 'boolean' ) {
  49. return value;
  50. }
  51. log.debug('tried boolean', { value })
  52. throw APIError.create('field_invalid', null, {
  53. key: this.srckey,
  54. expected: 'boolean',
  55. });
  56. }
  57. }