From 15c28b3d20befc4f6f89ec39f01ed662db376357 Mon Sep 17 00:00:00 2001 From: Anders Gustafsson <34234789+anders-photowall@users.noreply.github.com> Date: Wed, 22 Sep 2021 12:25:23 +0200 Subject: [PATCH] sanitize focus values (#52) --- src/datasources/product-api.ts | 11 ++++++++--- src/datasources/utils.ts | 17 +++++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/src/datasources/product-api.ts b/src/datasources/product-api.ts index 8ecd7a4..7518b07 100644 --- a/src/datasources/product-api.ts +++ b/src/datasources/product-api.ts @@ -18,7 +18,7 @@ import { ProductProportionsInput, } from '../types/product-types'; import { Maybe } from '../types/types'; -import { booleanStringField, nullOrNumber } from './utils'; +import { booleanStringField, nullOrNumber, roundOrDefaultTo } from './utils'; import { UserInputError } from 'apollo-server'; const MINUTE = 60; @@ -99,10 +99,15 @@ export class ProductAPI extends BaseSQLDataSource { fields['marginWidthMin'] = nullOrNumber(fields['marginWidthMin'] ?? null); fields['marginHeightMax'] = nullOrNumber(fields['marginHeightMax'] ?? null); fields['marginHeightMin'] = nullOrNumber(fields['marginHeightMin'] ?? null); - fields['focusXpoint2'] = nullOrNumber(fields['focusXpoint2'] ?? null); - fields['focusYpoint2'] = nullOrNumber(fields['focusYpoint2'] ?? null); fields['focusXpoint'] = nullOrNumber(fields['focusXpoint'] ?? null); fields['focusYpoint'] = nullOrNumber(fields['focusYpoint'] ?? null); + + // Focus points values are in %. + // Should be rounded to two decimals. Is sometimes missing in DB. + // If missing should be treated as 50%, 50% + fields['focusXpoint2'] = roundOrDefaultTo(fields['focusXpoint2'], 2, 50); + fields['focusYpoint2'] = roundOrDefaultTo(fields['focusYpoint2'], 2, 50); + fields['photowallResolution'] = nullOrNumber( fields['photowallResolution'] ?? null, ); diff --git a/src/datasources/utils.ts b/src/datasources/utils.ts index 87c21fd..9b1d7fd 100644 --- a/src/datasources/utils.ts +++ b/src/datasources/utils.ts @@ -15,6 +15,11 @@ function isBoolean(n: InputType | boolean) { return false; } +function roundToDecimals(number: number, decimalPlaces: number) { + const factor = Math.pow(10, decimalPlaces); + return Math.round((number + Number.EPSILON) * factor) / factor; +} + export function convertToPossibleType(n: InputType) { if ('' === n) return ''; if (isBoolean(n)) return Boolean(n); @@ -32,3 +37,15 @@ export function booleanStringField(v: string | null) { } return true; } + +export function roundOrDefaultTo( + v: string | null, + decimalPlaces: number, + defaultValue: number, +) { + if (!v) { + return defaultValue; + } + const number = parseFloat(v); + return roundToDecimals(number, decimalPlaces); +}