Skip to content

Commit

Permalink
#140 functional/immutable-dataの修正
Browse files Browse the repository at this point in the history
  • Loading branch information
FltSv committed Oct 20, 2024
1 parent 0bad9f7 commit dedb8f2
Show file tree
Hide file tree
Showing 5 changed files with 90 additions and 74 deletions.
3 changes: 2 additions & 1 deletion Hosting/eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ export default tseslint.config(
},
],
'functional/immutable-data': [
'warn', // オブジェクトの変更を警告
'error', // オブジェクトの変更を警告
{
ignoreImmediateMutation: true, // 変数に代入する前の即時変更を許可
ignoreClasses: true, // クラスの変更を許可
Expand All @@ -149,6 +149,7 @@ export default tseslint.config(
'window.location.href',
],
ignoreAccessorPattern: [
'window.**', // windowオブジェクトの変更を許可
'**.current.**', // React.useRefのcurrentプロパティへの変更を許可
'**.displayName', // React componentのdisplayNameプロパティへの変更を許可
'**.scrollTop', // スクロール位置の変更を許可
Expand Down
21 changes: 10 additions & 11 deletions Hosting/src/Auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,19 +39,18 @@ export const signupWithEmail = async (email: string, pass: string) => {

/** Googleログイン・新規登録 */
export const loginWith = async (providerType: providerTypes) => {
let provider;
switch (providerType) {
case 'google':
provider = new GoogleAuthProvider();
break;
const provider = (() => {
switch (providerType) {
case 'google':
return new GoogleAuthProvider();

case 'facebook':
provider = new FacebookAuthProvider();
break;
case 'facebook':
return new FacebookAuthProvider();

default:
throw new Error('Invalid provider type');
}
default:
throw new Error('Invalid provider type');
}
})();

// ポップアップでログイン
return await signInWithPopup(getAuth(), provider).catch((error: unknown) => {
Expand Down
85 changes: 50 additions & 35 deletions Hosting/src/Data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,6 @@ const getCreatorStorageUrl = (userId: string) =>
export const getCreatorData = async (user: User) => {
const userId = user.uid;
const creatorUrl = getCreatorStorageUrl(userId);
const creator: Creator = {
name: '',
profile: '',
links: [],
products: [],
exhibits: [],
};

// Firestoreからユーザーデータを取得
const docRef = doc(db, collectionNames.creators, userId).withConverter(
Expand All @@ -60,20 +53,28 @@ export const getCreatorData = async (user: User) => {
// 作家情報が存在しているか
if (!docSnap.exists()) {
// 存在しない場合、情報は空のままで登録を促す
return creator;
const empty: Creator = {
name: '',
profile: '',
links: [],
products: [],
exhibits: [],
};

return empty;
}

// ドキュメントが存在する場合、詳細を取得
const data = docSnap.data();
console.debug('docSnap.data:', data);

creator.name = data.name ?? '';
creator.profile = data.profile ?? '';
creator.links = data.links ?? [];
const name = data.name ?? '';
const profile = data.profile ?? '';
const links = data.links ?? [];

// 発表作品
const fbProducts = data.products ?? [];
creator.products = fbProducts.map(x => ({
const products = fbProducts.map(x => ({
id: x.id,
title: x.title ?? '',
detail: x.detail ?? '',
Expand All @@ -85,7 +86,7 @@ export const getCreatorData = async (user: User) => {
// 展示登録
const fbExhibits = data.exhibits ?? [];
const today = new Date();
creator.exhibits = fbExhibits.map(x => ({
const exhibits = fbExhibits.map(x => ({
id: x.id,
title: x.title,
location: x.location,
Expand All @@ -97,6 +98,14 @@ export const getCreatorData = async (user: User) => {
tmpImageData: '',
}));

const creator: Creator = {
name: name,
profile: profile,
links: links,
products: products,
exhibits: exhibits,
};

console.debug('creator:', creator);
return creator;
};
Expand All @@ -108,8 +117,8 @@ export const setCreatorData = async (user: User, data: Creator) => {
const userId = user.uid;

// 画像のアップロード
await uploadImageData(user, data.products);
await uploadImageData(user, data.exhibits);
const products = await uploadImageData(user, data.products);
const exhibits = await uploadImageData(user, data.exhibits);

// DB更新
const docRef = doc(db, collectionNames.creators, userId).withConverter(
Expand All @@ -119,13 +128,13 @@ export const setCreatorData = async (user: User, data: Creator) => {
name: data.name,
profile: data.profile,
links: data.links,
products: data.products.map(x => ({
products: products.map(x => ({
id: x.id,
title: x.title,
detail: x.detail,
image: x.srcImage,
})),
exhibits: data.exhibits.map(x => ({
exhibits: exhibits.map(x => ({
id: x.id,
title: x.title,
location: x.location,
Expand All @@ -138,7 +147,7 @@ export const setCreatorData = async (user: User, data: Creator) => {

// 使用されていない画像の削除
// 使用中の画像
const usingImages = [...data.products, ...data.exhibits].map(
const usingImages = [...products, ...exhibits].map(
(x: ImageStatus) => x.srcImage.split('?')[0],
);

Expand Down Expand Up @@ -169,11 +178,14 @@ export const setCreatorData = async (user: User, data: Creator) => {
/**
* tmpImageDataの画像をアップロード、URLを格納
*/
const uploadImageData = async (user: User, images: ImageStatus[]) => {
const uploadImage = async (image: ImageStatus) => {
const uploadImageData = async <T extends ImageStatus>(
user: User,
images: T[],
): Promise<T[]> => {
const uploadImage = async (image: T) => {
// イメージの更新が無ければスキップ
if (image.tmpImageData === '') {
return;
return image;
}

// blobURL→blobオブジェクトへ変換
Expand All @@ -192,11 +204,13 @@ const uploadImageData = async (user: User, images: ImageStatus[]) => {

const url = await getDownloadURL(result.ref);
const name = result.metadata.name;
image.srcImage = url.match(`${name}.*`)?.[0] ?? '';
const srcImage = url.match(`${name}.*`)?.[0] ?? '';
const newImage: T = { ...image, srcImage: srcImage };
return newImage;
};

const tasks = images.map(exhibit => uploadImage(exhibit));
await Promise.all(tasks);
const tasks = images.map(uploadImage);
return await Promise.all(tasks);
};

/** すべての展示情報の取得 */
Expand Down Expand Up @@ -242,17 +256,18 @@ export const getGalleryExhibits = async () => {
const galleries = await getGalleries();
const exhibits = await getAllExhibits();

const array: GalleryExhibits[] = [];

Map.groupBy(exhibits, x => x.location).forEach((value, key) => {
const gallery = galleries.find(x => x.name === key);
if (gallery === undefined) return;

array.push({
gallery: gallery,
exhibits: value,
});
});
const groupedExhibits = Map.groupBy(exhibits, x => x.location);

const array = Array.from(groupedExhibits.entries())
.map(([key, value]) => {
const gallery = galleries.find(x => x.name === key);
if (gallery === undefined) return null;
return {
gallery: gallery,
exhibits: value,
};
})
.filter((x): x is GalleryExhibits => x !== null);

return array;
};
Expand Down
47 changes: 24 additions & 23 deletions Hosting/src/components/pages/Mypage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -144,20 +144,19 @@ export const Mypage = () => {
if (files === null) return;
if (files.length === 0) return;

for (const file of Array.from(files)) {
const url = URL.createObjectURL(file);
const product: Product = {
id: getUlid(),
title: '',
detail: '',
tmpImageData: url,
srcImage: '',
imageUrl: '',
};
creator.products.push(product);
}

setCreator({ ...creator, products: creator.products });
const newProducts: Product[] = Array.from(files).map(file => ({
id: getUlid(),
title: '',
detail: '',
tmpImageData: URL.createObjectURL(file),
srcImage: '',
imageUrl: '',
}));

setCreator({
...creator,
products: [...creator.products, ...newProducts],
});
},
[creator],
);
Expand Down Expand Up @@ -278,21 +277,23 @@ export const Mypage = () => {

const onValid: SubmitHandler<Creator> = useCallback(
async data => {
// 一時データの結合
data.links = creator?.links ?? [];
data.products = creator?.products ?? [];
data.exhibits = creator?.exhibits ?? [];
if (user === null) return;
if (creator === undefined) return;

if (user === null) {
return;
}
// 一時データの結合
const submitData = {
...data,
links: creator.links,
products: creator.products,
exhibits: creator.exhibits,
};

// ローディングの表示
setIsSubmitting(true);

// 情報の送信
console.debug('submit: ', data);
await setCreatorData(user, data);
console.debug('submit: ', submitData);
await setCreatorData(user, submitData);

// リロード
window.location.reload();
Expand Down
8 changes: 4 additions & 4 deletions Hosting/src/firebase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,15 @@ export const db = getFirestore(app);

// Remote Config
// 最小フェッチ時間: dev1分、prod1時間
const config = getRemoteConfig(app);
config.settings.minimumFetchIntervalMillis =
const mut_config = getRemoteConfig(app);
mut_config.settings.minimumFetchIntervalMillis =
process.env.NODE_ENV === 'development' ? 60000 : 3600000;

export const getConfig = async (): Promise<Config> => {
await fetchAndActivate(config);
await fetchAndActivate(mut_config);
return {
debugUserIds: JSON.parse(
getValue(config, 'debug_user_ids').asString(),
getValue(mut_config, 'debug_user_ids').asString(),
) as string[],
};
};
Expand Down

0 comments on commit dedb8f2

Please sign in to comment.