Ads: move isExpired to tested utils function
This commit is contained in:
parent
f4af1687bf
commit
d5a066050f
3 changed files with 40 additions and 5 deletions
|
@ -2,6 +2,7 @@ import { useQuery } from '@tanstack/react-query';
|
|||
|
||||
import { Ad, getProvider } from 'soapbox/features/ads/providers';
|
||||
import { useAppDispatch } from 'soapbox/hooks';
|
||||
import { isExpired } from 'soapbox/utils/ads';
|
||||
|
||||
export default function useAds() {
|
||||
const dispatch = useAppDispatch();
|
||||
|
@ -22,11 +23,7 @@ export default function useAds() {
|
|||
});
|
||||
|
||||
// Filter out expired ads.
|
||||
const data = result.data?.filter(ad => {
|
||||
const now = new Date();
|
||||
const isExpired = ad.expires && (now.getTime() > ad.expires.getTime());
|
||||
return !isExpired;
|
||||
});
|
||||
const data = result.data?.filter(isExpired);
|
||||
|
||||
return {
|
||||
...result,
|
||||
|
|
22
app/soapbox/utils/__tests__/ads.test.ts
Normal file
22
app/soapbox/utils/__tests__/ads.test.ts
Normal file
|
@ -0,0 +1,22 @@
|
|||
import { normalizeCard } from 'soapbox/normalizers';
|
||||
|
||||
import { isExpired } from '../ads';
|
||||
|
||||
/** 3 minutes in milliseconds. */
|
||||
const threeMins = 3 * 60 * 1000;
|
||||
|
||||
/** 5 minutes in milliseconds. */
|
||||
const fiveMins = 5 * 60 * 1000;
|
||||
|
||||
test('isExpired()', () => {
|
||||
const now = new Date();
|
||||
const card = normalizeCard({});
|
||||
|
||||
// Sanity tests.
|
||||
expect(isExpired({ expires: now, card })).toBe(true);
|
||||
expect(isExpired({ expires: new Date(now.getTime() + 999999), card })).toBe(false);
|
||||
|
||||
// Testing the 5-minute mark.
|
||||
expect(isExpired({ expires: new Date(now.getTime() + threeMins), card }, fiveMins)).toBe(true);
|
||||
expect(isExpired({ expires: new Date(now.getTime() + fiveMins + 1000), card }, fiveMins)).toBe(false);
|
||||
});
|
16
app/soapbox/utils/ads.ts
Normal file
16
app/soapbox/utils/ads.ts
Normal file
|
@ -0,0 +1,16 @@
|
|||
import type { Ad } from 'soapbox/features/ads/providers';
|
||||
|
||||
/** Time (ms) window to not display an ad if it's about to expire. */
|
||||
const AD_EXPIRY_THRESHOLD = 5 * 60 * 1000;
|
||||
|
||||
/** Whether the ad is expired or about to expire. */
|
||||
const isExpired = (ad: Ad, threshold = AD_EXPIRY_THRESHOLD): boolean => {
|
||||
if (ad.expires) {
|
||||
const now = new Date();
|
||||
return now.getTime() > (ad.expires.getTime() - threshold);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
export { isExpired };
|
Loading…
Reference in a new issue