recent-search-recorder.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. interface RecentSearchResult {
  2. parent: string;
  3. page: string;
  4. title: string;
  5. url: string;
  6. timestamp: number;
  7. }
  8. const RECENT_SEARCHES_KEY = '__vendure_io_recent_searches__';
  9. export class RecentSearchRecorder {
  10. private recentSearches: RecentSearchResult[] = [];
  11. private readonly maxAgeMs = 5 * 24 * 60 * 60 * 1000; // 5 days
  12. private readonly maxSize = 5;
  13. get list() {
  14. return this.recentSearches.slice().reverse();
  15. }
  16. init() {
  17. try {
  18. const data = window.localStorage.getItem(RECENT_SEARCHES_KEY) ?? '[]';
  19. const parsed: RecentSearchResult[] = JSON.parse(data);
  20. const now = Date.now();
  21. this.recentSearches = parsed.filter(x => now - x.timestamp < this.maxAgeMs);
  22. } catch (e) {
  23. // ...
  24. }
  25. }
  26. record(details: Omit<RecentSearchResult, 'timestamp'>) {
  27. if (this.recentSearches.find(x => x.url === details.url)) {
  28. return;
  29. }
  30. this.recentSearches.push({
  31. ...details, timestamp: Date.now(),
  32. });
  33. if (this.maxSize < this.recentSearches.length) {
  34. this.recentSearches.shift();
  35. }
  36. window.localStorage.setItem(RECENT_SEARCHES_KEY, JSON.stringify(this.recentSearches));
  37. }
  38. }