Skip to content

Commit

Permalink
feat(watchhistory): store watchhistory in account
Browse files Browse the repository at this point in the history
  • Loading branch information
RCVZ committed Aug 2, 2021
1 parent 942849e commit 009315b
Show file tree
Hide file tree
Showing 5 changed files with 70 additions and 21 deletions.
7 changes: 4 additions & 3 deletions src/services/account.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ import type {
UpdateCustomerConsents,
RefreshToken,
GetLocales,
GetCaptureStatus, UpdateCaptureAnswers,
GetCaptureStatus,
UpdateCaptureAnswers,
} from '../../types/account';

import { post, put, patch, get } from './cleeng.service';
Expand Down Expand Up @@ -39,8 +40,8 @@ export const changePassword: ChangePassword = async (payload, sandbox) => {
return patch(sandbox, '/customers/passwords', JSON.stringify(payload));
};

export const updateCustomer: UpdateCustomer = async (payload, sandbox, jwt) => {
return patch(sandbox, `/customers/${payload.id}`, JSON.stringify(payload), jwt);
export const updateCustomer: UpdateCustomer = async ({ customerId, ...payload }, sandbox, jwt) => {
return patch(sandbox, `/customers/${customerId}`, JSON.stringify(payload), jwt);
};

export const updateCustomerConsents: UpdateCustomerConsents = async (payload, sandbox, jwt) => {
Expand Down
32 changes: 30 additions & 2 deletions src/stores/AccountStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ import * as subscriptionService from '../services/subscription.service';
import type { AuthData, Capture, Customer, JwtDetails, CustomerConsent } from '../../types/account';
import * as persist from '../utils/persist';
import type { Subscription } from '../../types/subscription';
import type { WatchHistoryItem } from '../../types/watchHistory';

import { ConfigStore } from './ConfigStore';
import { watchHistoryStore, restoreWatchHistory } from './WatchHistoryStore';

const PERSIST_KEY_ACCOUNT = 'auth';

Expand Down Expand Up @@ -59,6 +61,7 @@ export const initializeAccount = async () => {

if (refreshedAuthData) {
await afterLogin(config.cleengSandbox, refreshedAuthData);
restoreWatchHistory();
}
}
} catch (error: unknown) {
Expand Down Expand Up @@ -129,7 +132,9 @@ export const login = async (email: string, password: string) => {

if (response.errors.length > 0) throw new Error(response.errors[0]);

return afterLogin(cleengSandbox, response.responseData);
await afterLogin(cleengSandbox, response.responseData);

restoreWatchHistory();
};

export const logout = async () => {
Expand All @@ -146,6 +151,8 @@ export const register = async (email: string, password: string) => {
config: { cleengId, cleengSandbox },
} = ConfigStore.getRawState();

const { watchHistory } = watchHistoryStore.getRawState();

if (!cleengId) throw new Error('cleengId is not configured');

const localesResponse = await accountService.getLocales(cleengSandbox);
Expand All @@ -166,7 +173,28 @@ export const register = async (email: string, password: string) => {

if (responseRegister.errors.length) throw new Error(responseRegister.errors[0]);

return afterLogin(cleengSandbox, responseRegister.responseData);
await afterLogin(cleengSandbox, responseRegister.responseData);

if (watchHistory) {
setWatchHistory(watchHistory);
}

restoreWatchHistory();
};

export const setWatchHistory = async (watchHistory: WatchHistoryItem[]) => {
const { auth, user } = AccountStore.getRawState();

if (!auth || !user) throw new Error('no auth');

if (!watchHistory.length) return;

const {
config: { cleengSandbox },
} = ConfigStore.getRawState();

const externalData = { history: watchHistory };
return await accountService.updateCustomer({ customerId: user.id, externalData }, cleengSandbox, auth?.jwt);
};

export const updateConsents = async (customerConsents: CustomerConsent[]) => {
Expand Down
36 changes: 24 additions & 12 deletions src/stores/WatchHistoryStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import { PersonalShelf } from '../enum/PersonalShelf';
import { getMediaById } from '../services/api.service';
import * as persist from '../utils/persist';

import { AccountStore, setWatchHistory } from './AccountStore';

type WatchHistoryStore = {
watchHistory: WatchHistoryItem[];
playlistItemsLoaded: boolean;
Expand All @@ -20,31 +22,38 @@ export const watchHistoryStore = new Store<WatchHistoryStore>({
playlistItemsLoaded: false,
});

export const initializeWatchHistory = async () => {
const savedItems: WatchHistoryItem[] | null = persist.getItem(PERSIST_KEY_WATCH_HISTORY) as WatchHistoryItem[] | null;
export const restoreWatchHistory = async () => {
const { user } = AccountStore.getRawState();

const savedItems = user ? user.externalData?.history : persist.getItem<WatchHistoryItem[]>(PERSIST_KEY_WATCH_HISTORY);

if (savedItems) {
// Store persist data now, add playlistItems once API data ready
// Store savedItems immediately, so we can show the watchhistory while we fetch the mediaItems
watchHistoryStore.update((state) => {
state.watchHistory = savedItems;
});

const watchHistory = await Promise.all(
savedItems.map(async (item) =>
createWatchHistoryItem(await getMediaById(item.mediaid), { duration: item.duration, progress: item.progress }),
),
savedItems.map(async (item) => createWatchHistoryItem(await getMediaById(item.mediaid), { duration: item.duration, progress: item.progress })),
);

watchHistoryStore.update((state) => {
state.watchHistory = watchHistory.filter((item) => !!item.mediaid);
state.playlistItemsLoaded = true;
});
}
};

export const initializeWatchHistory = () => {
restoreWatchHistory();

const updateWatchHistory = (watchHistory: WatchHistoryItem[]) => {
const { user } = AccountStore.getRawState();

return watchHistoryStore.subscribe(
(state) => state.watchHistory,
(watchHistory) =>
persist.setItem(
if (user) {
return setWatchHistory(watchHistory);
} else {
return persist.setItem(
PERSIST_KEY_WATCH_HISTORY,
watchHistory.map(({ mediaid, title, tags, duration, progress }) => ({
mediaid,
Expand All @@ -53,8 +62,11 @@ export const initializeWatchHistory = async () => {
duration,
progress,
})),
),
);
);
}
};

return watchHistoryStore.subscribe((state) => state.watchHistory, updateWatchHistory);
};

export const createWatchHistoryItem = (item: PlaylistItem | undefined, videoProgress: VideoProgress): WatchHistoryItem => {
Expand Down
6 changes: 3 additions & 3 deletions src/utils/persist.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@ const setItem = (key: string, value: unknown) => {
}
};

const getItem = (key: string) => {
const getItem = <T>(key: string) => {
const storageKey = `${LOCAL_STORAGE_PREFIX}${key}`;

try {
return parseJSON(window.localStorage.getItem(storageKey));
return parseJSON<T>(window.localStorage.getItem(storageKey));
} catch (error: unknown) {
console.error(error);
}
Expand All @@ -37,7 +37,7 @@ const removeItem = (key: string) => {
}
};

const parseJSON = (value?: string | null): unknown | undefined => {
const parseJSON = <T>(value?: string | null): T | undefined => {
if (!value) return;

try {
Expand Down
10 changes: 9 additions & 1 deletion types/account.d.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { WatchHistoryItem } from './watchHistory';

export type AuthData = {
jwt: string;
customerToken: string;
Expand Down Expand Up @@ -150,6 +152,12 @@ export type UpdateCustomerPayload = {
confirmationPassword?: string;
firstName?: string;
lastName?: string;
customerId: number;
externalData?: ExternalData;
};

export type ExternalData = {
history: WatchHistoryItem[];
};

export type UpdateCustomerConsentsPayload = {
Expand All @@ -171,7 +179,7 @@ export type Customer = {
firstName?: string;
lastName?: string;
externalId?: string;
externalData?: Record<string, unknown>;
externalData?: ExternalData;
};

export type Consent = {
Expand Down

0 comments on commit 009315b

Please sign in to comment.