Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

52 lines
1.5KB

  1. import { CustomScalar, Scalar } from '@nestjs/graphql';
  2. import { GraphQLError, Kind, ValueNode } from 'graphql';
  3. const validate = (value: string): string => {
  4. const DATE_REGEX = /^(18|19|20)\d{2}-(0?[1-9]|1[0-2])-(0?[1-9]|[12]\d|3[01])( (0?[0-9]|1[0-9]|2[0-3]):(0?[0-9]|[1-5][0-9]):(0?[0-9]|[1-5][0-9]))?$/;
  5. if (typeof value !== 'string') {
  6. throw new TypeError(`Value is not string: ${value}`);
  7. }
  8. if (!DATE_REGEX.test(value)) {
  9. throw new TypeError(`Value is not a valid datetime: ${value}`);
  10. }
  11. const split = value.split(' ');
  12. if (split.length === 1) split.push('00:00:00');
  13. const tmp = split[0].split('-');
  14. if (tmp[1].length === 1) tmp[1] = '0' + tmp[1];
  15. if (tmp[2].length === 1) tmp[2] = '0' + tmp[2];
  16. split[0] = tmp.join('-');
  17. const time = split[1].split(':');
  18. if(time[0].length === 1) time[0] = '0' + time[0];
  19. if(time[1].length === 1) time[1] = '0' + time[1];
  20. if(time[2].length === 1) time[2] = '0' + time[2];
  21. split[1] = time.join(':');
  22. return split.join(' ');
  23. };
  24. @Scalar('DateTime', () => DateTime)
  25. export class DateTime implements CustomScalar<string, string> {
  26. description = 'A datetime string YYYY-MM-DD HH:MM:SS'
  27. parseValue(value: string): string {
  28. return validate(value)
  29. }
  30. serialize(value: string): string {
  31. return validate(value)
  32. }
  33. parseLiteral(ast: ValueNode): string {
  34. if (ast.kind !== Kind.STRING) {
  35. throw new GraphQLError(
  36. `Can only validate strings as date but got a: ${ast.kind}`,
  37. );
  38. }
  39. return validate(ast.value)
  40. }
  41. }