Merge pull request #42 from aaronpo97/react-toast

React toast updates and refactor
This commit is contained in:
Aaron Po
2023-05-22 22:52:41 -04:00
committed by GitHub
40 changed files with 577 additions and 358 deletions

View File

@@ -5,5 +5,8 @@ const nextConfig = {
domains: ['picsum.photos', 'res.cloudinary.com'], domains: ['picsum.photos', 'res.cloudinary.com'],
}, },
}; };
const withBundleAnalyzer = require('@next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
});
module.exports = nextConfig; module.exports = withBundleAnalyzer(nextConfig);

208
package-lock.json generated
View File

@@ -13,6 +13,7 @@
"@headlessui/tailwindcss": "^0.1.3", "@headlessui/tailwindcss": "^0.1.3",
"@hookform/resolvers": "^3.1.0", "@hookform/resolvers": "^3.1.0",
"@mapbox/mapbox-sdk": "^0.15.1", "@mapbox/mapbox-sdk": "^0.15.1",
"@next/bundle-analyzer": "^13.4.3",
"@prisma/client": "^4.13.0", "@prisma/client": "^4.13.0",
"@react-email/components": "^0.0.6", "@react-email/components": "^0.0.6",
"@react-email/render": "^0.0.7", "@react-email/render": "^0.0.7",
@@ -996,6 +997,14 @@
"node": ">=6.0.0" "node": ">=6.0.0"
} }
}, },
"node_modules/@next/bundle-analyzer": {
"version": "13.4.3",
"resolved": "https://registry.npmjs.org/@next/bundle-analyzer/-/bundle-analyzer-13.4.3.tgz",
"integrity": "sha512-jzWk6eaCFaIXfIswyQQWnR6FN22HpWoSWe3nLa3JCNkNd2ksriJgn86oQyZRxgAPaEbVKQXBp8GZi8e5DrhVJg==",
"dependencies": {
"webpack-bundle-analyzer": "4.7.0"
}
},
"node_modules/@next/env": { "node_modules/@next/env": {
"version": "13.3.4", "version": "13.3.4",
"resolved": "https://registry.npmjs.org/@next/env/-/env-13.3.4.tgz", "resolved": "https://registry.npmjs.org/@next/env/-/env-13.3.4.tgz",
@@ -1352,6 +1361,11 @@
"url": "https://opencollective.com/unts" "url": "https://opencollective.com/unts"
} }
}, },
"node_modules/@polka/url": {
"version": "1.0.0-next.21",
"resolved": "https://registry.npmjs.org/@polka/url/-/url-1.0.0-next.21.tgz",
"integrity": "sha512-a5Sab1C4/icpTZVzZc5Ghpz88yQtGOyNqYXcZgOssB2uuAr+wF/MvN6bgtW32q7HHrvBki+BsZ0OuNv6EV3K9g=="
},
"node_modules/@prisma/client": { "node_modules/@prisma/client": {
"version": "4.13.0", "version": "4.13.0",
"resolved": "https://registry.npmjs.org/@prisma/client/-/client-4.13.0.tgz", "resolved": "https://registry.npmjs.org/@prisma/client/-/client-4.13.0.tgz",
@@ -2382,7 +2396,6 @@
"version": "8.8.2", "version": "8.8.2",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.8.2.tgz", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.8.2.tgz",
"integrity": "sha512-xjIYgE8HBrkpd/sJqOGNspf8uHG+NOHGOw6a/Urj8taM2EXfdNAH2oFcPeIFfsv3+kz/mJrS5VuMqbNLjCa2vw==", "integrity": "sha512-xjIYgE8HBrkpd/sJqOGNspf8uHG+NOHGOw6a/Urj8taM2EXfdNAH2oFcPeIFfsv3+kz/mJrS5VuMqbNLjCa2vw==",
"devOptional": true,
"bin": { "bin": {
"acorn": "bin/acorn" "acorn": "bin/acorn"
}, },
@@ -2432,7 +2445,6 @@
"version": "8.2.0", "version": "8.2.0",
"resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.2.0.tgz", "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.2.0.tgz",
"integrity": "sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA==", "integrity": "sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA==",
"devOptional": true,
"engines": { "engines": {
"node": ">=0.4.0" "node": ">=0.4.0"
} }
@@ -4162,6 +4174,11 @@
"node": ">=12" "node": ">=12"
} }
}, },
"node_modules/duplexer": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/duplexer/-/duplexer-0.1.2.tgz",
"integrity": "sha512-jtD6YG370ZCIi/9GTaJKQxWTZD045+4R4hTk/x1UyoqadyJ9x9CgSi1RlVDQF8U2sxLLSnFkCaMihqljHIWgMg=="
},
"node_modules/duplexer2": { "node_modules/duplexer2": {
"version": "0.1.4", "version": "0.1.4",
"resolved": "https://registry.npmjs.org/duplexer2/-/duplexer2-0.1.4.tgz", "resolved": "https://registry.npmjs.org/duplexer2/-/duplexer2-0.1.4.tgz",
@@ -5779,6 +5796,20 @@
"resolved": "https://registry.npmjs.org/grid-index/-/grid-index-1.1.0.tgz", "resolved": "https://registry.npmjs.org/grid-index/-/grid-index-1.1.0.tgz",
"integrity": "sha512-HZRwumpOGUrHyxO5bqKZL0B0GlUpwtCAzZ42sgxUPniu33R1LSFH5yrIcBCHjkctCAh3mtWKcKd9J4vDDdeVHA==" "integrity": "sha512-HZRwumpOGUrHyxO5bqKZL0B0GlUpwtCAzZ42sgxUPniu33R1LSFH5yrIcBCHjkctCAh3mtWKcKd9J4vDDdeVHA=="
}, },
"node_modules/gzip-size": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/gzip-size/-/gzip-size-6.0.0.tgz",
"integrity": "sha512-ax7ZYomf6jqPTQ4+XCpUGyXKHk5WweS+e05MBO4/y3WJ5RkmPXNKvX+bx1behVILVwr6JSQvZAku021CHPXG3Q==",
"dependencies": {
"duplexer": "^0.1.2"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/har-schema": { "node_modules/har-schema": {
"version": "2.0.0", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz", "resolved": "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz",
@@ -7807,6 +7838,14 @@
"node": ">=4" "node": ">=4"
} }
}, },
"node_modules/mrmime": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/mrmime/-/mrmime-1.0.1.tgz",
"integrity": "sha512-hzzEagAgDyoU1Q6yg5uI+AorQgdvMCur3FcKf7NhMKWsaYg+RnbTyHRa/9IlLF9rf455MOCtcqqrQQ83pPP7Uw==",
"engines": {
"node": ">=10"
}
},
"node_modules/ms": { "node_modules/ms": {
"version": "2.1.2", "version": "2.1.2",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
@@ -8281,6 +8320,14 @@
"url": "https://github.com/sponsors/sindresorhus" "url": "https://github.com/sponsors/sindresorhus"
} }
}, },
"node_modules/opener": {
"version": "1.5.2",
"resolved": "https://registry.npmjs.org/opener/-/opener-1.5.2.tgz",
"integrity": "sha512-ur5UIdyw5Y7yEj9wLzhqXiy6GZ3Mwx0yGI+5sMn2r0N0v3cKJvUmFH5yPP+WXh9e0xfyzyJX95D8l088DNFj7A==",
"bin": {
"opener": "bin/opener-bin.js"
}
},
"node_modules/optionator": { "node_modules/optionator": {
"version": "0.9.1", "version": "0.9.1",
"resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.1.tgz", "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.1.tgz",
@@ -10032,6 +10079,19 @@
"resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.2.tgz", "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.2.tgz",
"integrity": "sha512-eVRqCvVlZbuw3GrM63ovNSNAeA1K16kaR/LRY/92w0zxQ5/1YzwblUX652i4Xs9RwAGjW9d9y6X88t8OaAJfWQ==" "integrity": "sha512-eVRqCvVlZbuw3GrM63ovNSNAeA1K16kaR/LRY/92w0zxQ5/1YzwblUX652i4Xs9RwAGjW9d9y6X88t8OaAJfWQ=="
}, },
"node_modules/sirv": {
"version": "1.0.19",
"resolved": "https://registry.npmjs.org/sirv/-/sirv-1.0.19.tgz",
"integrity": "sha512-JuLThK3TnZG1TAKDwNIqNq6QA2afLOCcm+iE8D1Kj3GA40pSPsxQjjJl0J8X3tsR7T+CP1GavpzLwYkgVLWrZQ==",
"dependencies": {
"@polka/url": "^1.0.0-next.20",
"mrmime": "^1.0.0",
"totalist": "^1.0.0"
},
"engines": {
"node": ">= 10"
}
},
"node_modules/slash": { "node_modules/slash": {
"version": "3.0.0", "version": "3.0.0",
"resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz",
@@ -10648,6 +10708,14 @@
"node": ">=0.6" "node": ">=0.6"
} }
}, },
"node_modules/totalist": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/totalist/-/totalist-1.1.0.tgz",
"integrity": "sha512-gduQwd1rOdDMGxFG1gEvhV88Oirdo2p+KjoYFU7k2g+i7n6AFFbDQ5kMPUsW0pNbfQsB/cwXvT1i4Bue0s9g5g==",
"engines": {
"node": ">=6"
}
},
"node_modules/tough-cookie": { "node_modules/tough-cookie": {
"version": "2.5.0", "version": "2.5.0",
"resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.5.0.tgz", "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.5.0.tgz",
@@ -11294,6 +11362,36 @@
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==" "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="
}, },
"node_modules/webpack-bundle-analyzer": {
"version": "4.7.0",
"resolved": "https://registry.npmjs.org/webpack-bundle-analyzer/-/webpack-bundle-analyzer-4.7.0.tgz",
"integrity": "sha512-j9b8ynpJS4K+zfO5GGwsAcQX4ZHpWV+yRiHDiL+bE0XHJ8NiPYLTNVQdlFYWxtpg9lfAQNlwJg16J9AJtFSXRg==",
"dependencies": {
"acorn": "^8.0.4",
"acorn-walk": "^8.0.0",
"chalk": "^4.1.0",
"commander": "^7.2.0",
"gzip-size": "^6.0.0",
"lodash": "^4.17.20",
"opener": "^1.5.2",
"sirv": "^1.0.7",
"ws": "^7.3.1"
},
"bin": {
"webpack-bundle-analyzer": "lib/bin/analyzer.js"
},
"engines": {
"node": ">= 10.13.0"
}
},
"node_modules/webpack-bundle-analyzer/node_modules/commander": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz",
"integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==",
"engines": {
"node": ">= 10"
}
},
"node_modules/whatwg-url": { "node_modules/whatwg-url": {
"version": "5.0.0", "version": "5.0.0",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
@@ -11390,6 +11488,26 @@
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==" "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="
}, },
"node_modules/ws": {
"version": "7.5.9",
"resolved": "https://registry.npmjs.org/ws/-/ws-7.5.9.tgz",
"integrity": "sha512-F+P9Jil7UiSKSkppIiD94dN07AwvFixvLIj1Og1Rl9GGMuNipJnV9JzjD6XuqmAeiswGvUmNLjr5cFuXwNS77Q==",
"engines": {
"node": ">=8.3.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": "^5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
},
"node_modules/xregexp": { "node_modules/xregexp": {
"version": "2.0.0", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/xregexp/-/xregexp-2.0.0.tgz", "resolved": "https://registry.npmjs.org/xregexp/-/xregexp-2.0.0.tgz",
@@ -12050,6 +12168,14 @@
"resolved": "https://registry.npmjs.org/@mapbox/whoots-js/-/whoots-js-3.1.0.tgz", "resolved": "https://registry.npmjs.org/@mapbox/whoots-js/-/whoots-js-3.1.0.tgz",
"integrity": "sha512-Es6WcD0nO5l+2BOQS4uLfNPYQaNDfbot3X1XUoloz+x0mPDS3eeORZJl06HXjwBG1fOGwCRnzK88LMdxKRrd6Q==" "integrity": "sha512-Es6WcD0nO5l+2BOQS4uLfNPYQaNDfbot3X1XUoloz+x0mPDS3eeORZJl06HXjwBG1fOGwCRnzK88LMdxKRrd6Q=="
}, },
"@next/bundle-analyzer": {
"version": "13.4.3",
"resolved": "https://registry.npmjs.org/@next/bundle-analyzer/-/bundle-analyzer-13.4.3.tgz",
"integrity": "sha512-jzWk6eaCFaIXfIswyQQWnR6FN22HpWoSWe3nLa3JCNkNd2ksriJgn86oQyZRxgAPaEbVKQXBp8GZi8e5DrhVJg==",
"requires": {
"webpack-bundle-analyzer": "4.7.0"
}
},
"@next/env": { "@next/env": {
"version": "13.3.4", "version": "13.3.4",
"resolved": "https://registry.npmjs.org/@next/env/-/env-13.3.4.tgz", "resolved": "https://registry.npmjs.org/@next/env/-/env-13.3.4.tgz",
@@ -12272,6 +12398,11 @@
"tslib": "^2.5.0" "tslib": "^2.5.0"
} }
}, },
"@polka/url": {
"version": "1.0.0-next.21",
"resolved": "https://registry.npmjs.org/@polka/url/-/url-1.0.0-next.21.tgz",
"integrity": "sha512-a5Sab1C4/icpTZVzZc5Ghpz88yQtGOyNqYXcZgOssB2uuAr+wF/MvN6bgtW32q7HHrvBki+BsZ0OuNv6EV3K9g=="
},
"@prisma/client": { "@prisma/client": {
"version": "4.13.0", "version": "4.13.0",
"resolved": "https://registry.npmjs.org/@prisma/client/-/client-4.13.0.tgz", "resolved": "https://registry.npmjs.org/@prisma/client/-/client-4.13.0.tgz",
@@ -13113,8 +13244,7 @@
"acorn": { "acorn": {
"version": "8.8.2", "version": "8.8.2",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.8.2.tgz", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.8.2.tgz",
"integrity": "sha512-xjIYgE8HBrkpd/sJqOGNspf8uHG+NOHGOw6a/Urj8taM2EXfdNAH2oFcPeIFfsv3+kz/mJrS5VuMqbNLjCa2vw==", "integrity": "sha512-xjIYgE8HBrkpd/sJqOGNspf8uHG+NOHGOw6a/Urj8taM2EXfdNAH2oFcPeIFfsv3+kz/mJrS5VuMqbNLjCa2vw=="
"devOptional": true
}, },
"acorn-jsx": { "acorn-jsx": {
"version": "5.3.2", "version": "5.3.2",
@@ -13148,8 +13278,7 @@
"acorn-walk": { "acorn-walk": {
"version": "8.2.0", "version": "8.2.0",
"resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.2.0.tgz", "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.2.0.tgz",
"integrity": "sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA==", "integrity": "sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA=="
"devOptional": true
}, },
"agent-base": { "agent-base": {
"version": "6.0.2", "version": "6.0.2",
@@ -14373,6 +14502,11 @@
"integrity": "sha512-GopVGCpVS1UKH75VKHGuQFqS1Gusej0z4FyQkPdwjil2gNIv+LNsqBlboOzpJFZKVT95GkCyWJbBSdFEFUWI2A==", "integrity": "sha512-GopVGCpVS1UKH75VKHGuQFqS1Gusej0z4FyQkPdwjil2gNIv+LNsqBlboOzpJFZKVT95GkCyWJbBSdFEFUWI2A==",
"dev": true "dev": true
}, },
"duplexer": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/duplexer/-/duplexer-0.1.2.tgz",
"integrity": "sha512-jtD6YG370ZCIi/9GTaJKQxWTZD045+4R4hTk/x1UyoqadyJ9x9CgSi1RlVDQF8U2sxLLSnFkCaMihqljHIWgMg=="
},
"duplexer2": { "duplexer2": {
"version": "0.1.4", "version": "0.1.4",
"resolved": "https://registry.npmjs.org/duplexer2/-/duplexer2-0.1.4.tgz", "resolved": "https://registry.npmjs.org/duplexer2/-/duplexer2-0.1.4.tgz",
@@ -15628,6 +15762,14 @@
"resolved": "https://registry.npmjs.org/grid-index/-/grid-index-1.1.0.tgz", "resolved": "https://registry.npmjs.org/grid-index/-/grid-index-1.1.0.tgz",
"integrity": "sha512-HZRwumpOGUrHyxO5bqKZL0B0GlUpwtCAzZ42sgxUPniu33R1LSFH5yrIcBCHjkctCAh3mtWKcKd9J4vDDdeVHA==" "integrity": "sha512-HZRwumpOGUrHyxO5bqKZL0B0GlUpwtCAzZ42sgxUPniu33R1LSFH5yrIcBCHjkctCAh3mtWKcKd9J4vDDdeVHA=="
}, },
"gzip-size": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/gzip-size/-/gzip-size-6.0.0.tgz",
"integrity": "sha512-ax7ZYomf6jqPTQ4+XCpUGyXKHk5WweS+e05MBO4/y3WJ5RkmPXNKvX+bx1behVILVwr6JSQvZAku021CHPXG3Q==",
"requires": {
"duplexer": "^0.1.2"
}
},
"har-schema": { "har-schema": {
"version": "2.0.0", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz", "resolved": "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz",
@@ -17009,6 +17151,11 @@
"integrity": "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==", "integrity": "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==",
"dev": true "dev": true
}, },
"mrmime": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/mrmime/-/mrmime-1.0.1.tgz",
"integrity": "sha512-hzzEagAgDyoU1Q6yg5uI+AorQgdvMCur3FcKf7NhMKWsaYg+RnbTyHRa/9IlLF9rf455MOCtcqqrQQ83pPP7Uw=="
},
"ms": { "ms": {
"version": "2.1.2", "version": "2.1.2",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
@@ -17328,6 +17475,11 @@
"is-wsl": "^2.2.0" "is-wsl": "^2.2.0"
} }
}, },
"opener": {
"version": "1.5.2",
"resolved": "https://registry.npmjs.org/opener/-/opener-1.5.2.tgz",
"integrity": "sha512-ur5UIdyw5Y7yEj9wLzhqXiy6GZ3Mwx0yGI+5sMn2r0N0v3cKJvUmFH5yPP+WXh9e0xfyzyJX95D8l088DNFj7A=="
},
"optionator": { "optionator": {
"version": "0.9.1", "version": "0.9.1",
"resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.1.tgz", "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.1.tgz",
@@ -18528,6 +18680,16 @@
} }
} }
}, },
"sirv": {
"version": "1.0.19",
"resolved": "https://registry.npmjs.org/sirv/-/sirv-1.0.19.tgz",
"integrity": "sha512-JuLThK3TnZG1TAKDwNIqNq6QA2afLOCcm+iE8D1Kj3GA40pSPsxQjjJl0J8X3tsR7T+CP1GavpzLwYkgVLWrZQ==",
"requires": {
"@polka/url": "^1.0.0-next.20",
"mrmime": "^1.0.0",
"totalist": "^1.0.0"
}
},
"slash": { "slash": {
"version": "3.0.0", "version": "3.0.0",
"resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz",
@@ -18995,6 +19157,11 @@
"integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
"optional": true "optional": true
}, },
"totalist": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/totalist/-/totalist-1.1.0.tgz",
"integrity": "sha512-gduQwd1rOdDMGxFG1gEvhV88Oirdo2p+KjoYFU7k2g+i7n6AFFbDQ5kMPUsW0pNbfQsB/cwXvT1i4Bue0s9g5g=="
},
"tough-cookie": { "tough-cookie": {
"version": "2.5.0", "version": "2.5.0",
"resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.5.0.tgz", "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.5.0.tgz",
@@ -19457,6 +19624,29 @@
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==" "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="
}, },
"webpack-bundle-analyzer": {
"version": "4.7.0",
"resolved": "https://registry.npmjs.org/webpack-bundle-analyzer/-/webpack-bundle-analyzer-4.7.0.tgz",
"integrity": "sha512-j9b8ynpJS4K+zfO5GGwsAcQX4ZHpWV+yRiHDiL+bE0XHJ8NiPYLTNVQdlFYWxtpg9lfAQNlwJg16J9AJtFSXRg==",
"requires": {
"acorn": "^8.0.4",
"acorn-walk": "^8.0.0",
"chalk": "^4.1.0",
"commander": "^7.2.0",
"gzip-size": "^6.0.0",
"lodash": "^4.17.20",
"opener": "^1.5.2",
"sirv": "^1.0.7",
"ws": "^7.3.1"
},
"dependencies": {
"commander": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz",
"integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw=="
}
}
},
"whatwg-url": { "whatwg-url": {
"version": "5.0.0", "version": "5.0.0",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
@@ -19532,6 +19722,12 @@
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==" "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="
}, },
"ws": {
"version": "7.5.9",
"resolved": "https://registry.npmjs.org/ws/-/ws-7.5.9.tgz",
"integrity": "sha512-F+P9Jil7UiSKSkppIiD94dN07AwvFixvLIj1Og1Rl9GGMuNipJnV9JzjD6XuqmAeiswGvUmNLjr5cFuXwNS77Q==",
"requires": {}
},
"xregexp": { "xregexp": {
"version": "2.0.0", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/xregexp/-/xregexp-2.0.0.tgz", "resolved": "https://registry.npmjs.org/xregexp/-/xregexp-2.0.0.tgz",

View File

@@ -16,6 +16,7 @@
"@headlessui/tailwindcss": "^0.1.3", "@headlessui/tailwindcss": "^0.1.3",
"@hookform/resolvers": "^3.1.0", "@hookform/resolvers": "^3.1.0",
"@mapbox/mapbox-sdk": "^0.15.1", "@mapbox/mapbox-sdk": "^0.15.1",
"@next/bundle-analyzer": "^13.4.3",
"@prisma/client": "^4.13.0", "@prisma/client": "^4.13.0",
"@react-email/components": "^0.0.6", "@react-email/components": "^0.0.6",
"@react-email/render": "^0.0.7", "@react-email/render": "^0.0.7",

View File

@@ -1,24 +1,23 @@
import validateEmail from '@/requests/valdiateEmail'; import validateEmailRequest from '@/requests/User/validateEmailRequest';
import validateUsername from '@/requests/validateUsername'; import validateUsernameRequest from '@/requests/validateUsernameRequest';
import { BaseCreateUserSchema } from '@/services/User/schema/CreateUserValidationSchemas'; import { BaseCreateUserSchema } from '@/services/User/schema/CreateUserValidationSchemas';
import GetUserSchema from '@/services/User/schema/GetUserSchema';
import { Switch } from '@headlessui/react'; import { Switch } from '@headlessui/react';
import { zodResolver } from '@hookform/resolvers/zod'; import { zodResolver } from '@hookform/resolvers/zod';
import { useRouter } from 'next/router'; import { FC, useContext, useState } from 'react';
import { FC, useState } from 'react';
import { useForm } from 'react-hook-form'; import { useForm } from 'react-hook-form';
import { z } from 'zod'; import { z } from 'zod';
import UserContext from '@/contexts/UserContext';
import sendEditUserRequest from '@/requests/User/sendEditUserRequest';
import createErrorToast from '@/util/createErrorToast';
import { toast } from 'react-hot-toast';
import FormError from '../ui/forms/FormError'; import FormError from '../ui/forms/FormError';
import FormInfo from '../ui/forms/FormInfo'; import FormInfo from '../ui/forms/FormInfo';
import FormLabel from '../ui/forms/FormLabel'; import FormLabel from '../ui/forms/FormLabel';
import FormTextInput from '../ui/forms/FormTextInput'; import FormTextInput from '../ui/forms/FormTextInput';
interface AccountInfoProps { const AccountInfo: FC = () => {
user: z.infer<typeof GetUserSchema>; const { user, mutate } = useContext(UserContext);
}
const AccountInfo: FC<AccountInfoProps> = ({ user }) => {
const router = useRouter();
const EditUserSchema = BaseCreateUserSchema.pick({ const EditUserSchema = BaseCreateUserSchema.pick({
username: true, username: true,
email: true, email: true,
@@ -30,8 +29,8 @@ const AccountInfo: FC<AccountInfoProps> = ({ user }) => {
.email({ message: 'Email must be a valid email address.' }) .email({ message: 'Email must be a valid email address.' })
.refine( .refine(
async (email) => { async (email) => {
if (user.email === email) return true; if (user!.email === email) return true;
return validateEmail(email); return validateEmailRequest(email);
}, },
{ message: 'Email is already taken.' }, { message: 'Email is already taken.' },
), ),
@@ -41,8 +40,8 @@ const AccountInfo: FC<AccountInfoProps> = ({ user }) => {
.max(20, { message: 'Username must be less than 20 characters.' }) .max(20, { message: 'Username must be less than 20 characters.' })
.refine( .refine(
async (username) => { async (username) => {
if (user.username === username) return true; if (user!.username === username) return true;
return validateUsername(username); return validateUsernameRequest(username);
}, },
{ message: 'Username is already taken.' }, { message: 'Username is already taken.' },
), ),
@@ -53,29 +52,29 @@ const AccountInfo: FC<AccountInfoProps> = ({ user }) => {
>({ >({
resolver: zodResolver(EditUserSchema), resolver: zodResolver(EditUserSchema),
defaultValues: { defaultValues: {
username: user.username, username: user!.username,
email: user.email, email: user!.email,
firstName: user.firstName, firstName: user!.firstName,
lastName: user.lastName, lastName: user!.lastName,
}, },
}); });
const [inEditMode, setInEditMode] = useState(false); const [inEditMode, setInEditMode] = useState(false);
const onSubmit = async (data: z.infer<typeof EditUserSchema>) => { const onSubmit = async (data: z.infer<typeof EditUserSchema>) => {
const response = await fetch(`/api/users/${user.id}/edit`, { const loadingToast = toast.loading('Submitting edits...');
body: JSON.stringify(data), try {
method: 'PUT', await sendEditUserRequest({ user: user!, data });
headers: { 'Content-Type': 'application/json' }, await mutate!();
}); setInEditMode(false);
toast.remove(loadingToast);
if (!response.ok) { toast.success('Edits submitted successfully.');
throw new Error('Something went wrong.'); } catch (error) {
setInEditMode(false);
toast.remove(loadingToast);
createErrorToast(error);
await mutate!();
} }
await response.json();
router.reload();
}; };
return ( return (

View File

@@ -2,7 +2,8 @@ import UserContext from '@/contexts/UserContext';
import useTimeDistance from '@/hooks/utilities/useTimeDistance'; import useTimeDistance from '@/hooks/utilities/useTimeDistance';
import { format } from 'date-fns'; import { format } from 'date-fns';
import { Dispatch, FC, SetStateAction, useContext } from 'react'; import { Dispatch, FC, SetStateAction, useContext } from 'react';
import { Link, Rating } from 'react-daisyui'; import { Rating } from 'react-daisyui';
import Link from 'next/link';
import CommentQueryResult from '@/services/types/CommentSchema/CommentQueryResult'; import CommentQueryResult from '@/services/types/CommentSchema/CommentQueryResult';
import { z } from 'zod'; import { z } from 'zod';

View File

@@ -1,5 +1,5 @@
import { zodResolver } from '@hookform/resolvers/zod'; import { zodResolver } from '@hookform/resolvers/zod';
import { FC, useState, Dispatch, SetStateAction, useContext } from 'react'; import { FC, useState, Dispatch, SetStateAction } from 'react';
import { Rating } from 'react-daisyui'; import { Rating } from 'react-daisyui';
import { useForm, SubmitHandler } from 'react-hook-form'; import { useForm, SubmitHandler } from 'react-hook-form';
import { z } from 'zod'; import { z } from 'zod';
@@ -7,7 +7,8 @@ import useBeerPostComments from '@/hooks/data-fetching/beer-comments/useBeerPost
import CommentQueryResult from '@/services/types/CommentSchema/CommentQueryResult'; import CommentQueryResult from '@/services/types/CommentSchema/CommentQueryResult';
import CreateCommentValidationSchema from '@/services/types/CommentSchema/CreateCommentValidationSchema'; import CreateCommentValidationSchema from '@/services/types/CommentSchema/CreateCommentValidationSchema';
import useBreweryPostComments from '@/hooks/data-fetching/brewery-comments/useBreweryPostComments'; import useBreweryPostComments from '@/hooks/data-fetching/brewery-comments/useBreweryPostComments';
import ToastContext from '@/contexts/ToastContext'; import toast from 'react-hot-toast';
import createErrorToast from '@/util/createErrorToast';
import FormError from '../ui/forms/FormError'; import FormError from '../ui/forms/FormError';
import FormInfo from '../ui/forms/FormInfo'; import FormInfo from '../ui/forms/FormInfo';
import FormLabel from '../ui/forms/FormLabel'; import FormLabel from '../ui/forms/FormLabel';
@@ -31,7 +32,6 @@ interface EditCommentBodyProps {
const EditCommentBody: FC<EditCommentBodyProps> = ({ const EditCommentBody: FC<EditCommentBodyProps> = ({
comment, comment,
setInEditMode, setInEditMode,
mutate, mutate,
handleDeleteRequest, handleDeleteRequest,
handleEditRequest, handleEditRequest,
@@ -43,25 +43,41 @@ const EditCommentBody: FC<EditCommentBodyProps> = ({
resolver: zodResolver(CreateCommentValidationSchema), resolver: zodResolver(CreateCommentValidationSchema),
}); });
const { toast } = useContext(ToastContext); const { errors, isSubmitting } = formState;
const { errors } = formState;
const [isDeleting, setIsDeleting] = useState(false); const [isDeleting, setIsDeleting] = useState(false);
const onDelete = async () => { const onDelete = async () => {
const loadingToast = toast.loading('Deleting comment...');
setIsDeleting(true); setIsDeleting(true);
try {
await handleDeleteRequest(comment.id); await handleDeleteRequest(comment.id);
await mutate(); await mutate();
toast.remove(loadingToast);
toast.success('Deleted comment.');
} catch (error) {
toast.remove(loadingToast);
createErrorToast(error);
}
}; };
const onEdit: SubmitHandler<z.infer<typeof CreateCommentValidationSchema>> = async ( const onEdit: SubmitHandler<z.infer<typeof CreateCommentValidationSchema>> = async (
data, data,
) => { ) => {
const loadingToast = toast.loading('Submitting comment edits...');
try {
setInEditMode(true); setInEditMode(true);
await handleEditRequest(comment.id, data); await handleEditRequest(comment.id, data);
await mutate(); await mutate();
toast.success('Submitted edits'); toast.remove(loadingToast);
toast.success('Comment edits submitted successfully.');
setInEditMode(false); setInEditMode(false);
} catch (error) {
toast.remove(loadingToast);
createErrorToast(error);
setInEditMode(false);
}
}; };
return ( return (
@@ -79,7 +95,7 @@ const EditCommentBody: FC<EditCommentBodyProps> = ({
placeholder="Comment" placeholder="Comment"
rows={2} rows={2}
error={!!errors.content?.message} error={!!errors.content?.message}
disabled={formState.isSubmitting || isDeleting} disabled={isSubmitting || isDeleting}
/> />
</FormSegment> </FormSegment>
<div className="flex flex-row items-center justify-between"> <div className="flex flex-row items-center justify-between">
@@ -98,8 +114,8 @@ const EditCommentBody: FC<EditCommentBodyProps> = ({
<Rating.Item <Rating.Item
name="rating-1" name="rating-1"
className="mask mask-star cursor-default" className="mask mask-star cursor-default"
disabled={formState.isSubmitting || isDeleting} disabled={isSubmitting || isDeleting}
aria-disabled={formState.isSubmitting || isDeleting} aria-disabled={isSubmitting || isDeleting}
key={index} key={index}
/> />
))} ))}
@@ -109,7 +125,7 @@ const EditCommentBody: FC<EditCommentBodyProps> = ({
<button <button
type="button" type="button"
className="btn-xs btn lg:btn-sm" className="btn-xs btn lg:btn-sm"
disabled={formState.isSubmitting || isDeleting} disabled={isSubmitting || isDeleting}
onClick={() => { onClick={() => {
setInEditMode(false); setInEditMode(false);
}} }}
@@ -118,7 +134,7 @@ const EditCommentBody: FC<EditCommentBodyProps> = ({
</button> </button>
<button <button
type="submit" type="submit"
disabled={formState.isSubmitting || isDeleting} disabled={isSubmitting || isDeleting}
className="btn-xs btn lg:btn-sm" className="btn-xs btn lg:btn-sm"
> >
Save Save

View File

@@ -1,4 +1,4 @@
import sendCreateBeerCommentRequest from '@/requests/sendCreateBeerCommentRequest'; import sendCreateBeerCommentRequest from '@/requests/BeerComment/sendCreateBeerCommentRequest';
import beerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult'; import beerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
import { zodResolver } from '@hookform/resolvers/zod'; import { zodResolver } from '@hookform/resolvers/zod';
@@ -9,6 +9,8 @@ import { z } from 'zod';
import useBeerPostComments from '@/hooks/data-fetching/beer-comments/useBeerPostComments'; import useBeerPostComments from '@/hooks/data-fetching/beer-comments/useBeerPostComments';
import CreateCommentValidationSchema from '@/services/types/CommentSchema/CreateCommentValidationSchema'; import CreateCommentValidationSchema from '@/services/types/CommentSchema/CreateCommentValidationSchema';
import toast from 'react-hot-toast';
import createErrorToast from '@/util/createErrorToast';
import CommentForm from '../ui/CommentForm'; import CommentForm from '../ui/CommentForm';
interface BeerCommentFormProps { interface BeerCommentFormProps {
@@ -30,13 +32,23 @@ const BeerCommentForm: FunctionComponent<BeerCommentFormProps> = ({
const onSubmit: SubmitHandler<z.infer<typeof CreateCommentValidationSchema>> = async ( const onSubmit: SubmitHandler<z.infer<typeof CreateCommentValidationSchema>> = async (
data, data,
) => { ) => {
const loadingToast = toast.loading('Posting a new comment...');
try {
await sendCreateBeerCommentRequest({ await sendCreateBeerCommentRequest({
content: data.content, content: data.content,
rating: data.rating, rating: data.rating,
beerPostId: beerPost.id, beerPostId: beerPost.id,
}); });
await mutate();
reset(); reset();
toast.remove(loadingToast);
toast.success('Comment posted successfully.');
await mutate();
} catch (error) {
await mutate();
toast.remove(loadingToast);
createErrorToast(error);
reset();
}
}; };
return ( return (

View File

@@ -67,8 +67,8 @@ const BeerPostCommentsSection: FC<BeerPostCommentsSectionProps> = ({ beerPost })
{ {
/** /**
* If the comments are loading, show a loading component. Otherwise, show the * If the comments are loading, show a loading component. Otherwise, show
* comments. * the comments.
*/ */
isLoading ? ( isLoading ? (
<div className="card bg-base-300 pb-6"> <div className="card bg-base-300 pb-6">

View File

@@ -1,8 +1,9 @@
import useCheckIfUserLikesBeerPost from '@/hooks/data-fetching/beer-likes/useCheckIfUserLikesBeerPost'; import useCheckIfUserLikesBeerPost from '@/hooks/data-fetching/beer-likes/useCheckIfUserLikesBeerPost';
import sendBeerPostLikeRequest from '@/requests/sendBeerPostLikeRequest';
import { FC, useEffect, useState } from 'react'; import { FC, useEffect, useState } from 'react';
import useGetBeerPostLikeCount from '@/hooks/data-fetching/beer-likes/useBeerPostLikeCount'; import useGetBeerPostLikeCount from '@/hooks/data-fetching/beer-likes/useBeerPostLikeCount';
import sendBeerPostLikeRequest from '@/requests/BeerPost/sendBeerPostLikeRequest';
import LikeButton from '../ui/LikeButton'; import LikeButton from '../ui/LikeButton';
const BeerPostLikeButton: FC<{ const BeerPostLikeButton: FC<{

View File

@@ -19,8 +19,8 @@ const BeerRecommendationsSection: FC<{
const { ref: penultimateBeerPostRef } = useInView({ const { ref: penultimateBeerPostRef } = useInView({
/** /**
* When the last beer post comes into view, call setSize from useBeerPostsByBrewery to * When the last beer post comes into view, call setSize from
* load more beer posts. * useBeerPostsByBrewery to load more beer posts.
*/ */
onChange: (visible) => { onChange: (visible) => {
if (!visible || isAtEnd) return; if (!visible || isAtEnd) return;
@@ -46,8 +46,9 @@ const BeerRecommendationsSection: FC<{
const isPenultimateBeerPost = index === beerPosts.length - 2; const isPenultimateBeerPost = index === beerPosts.length - 2;
/** /**
* Attach a ref to the second last beer post in the list. When it comes * Attach a ref to the second last beer post in the list.
* into view, the component will call setSize to load more beer posts. * When it comes into view, the component will call
* setSize to load more beer posts.
*/ */
return ( return (
@@ -85,8 +86,8 @@ const BeerRecommendationsSection: FC<{
{ {
/** /**
* If there are more beer posts to load, show a loading component with a * If there are more beer posts to load, show a loading component
* skeleton loader and a loading spinner. * with a skeleton loader and a loading spinner.
*/ */
!!isLoadingMore && !isAtEnd && ( !!isLoadingMore && !isAtEnd && (
<BeerRecommendationLoadingComponent length={PAGE_SIZE} /> <BeerRecommendationLoadingComponent length={PAGE_SIZE} />

View File

@@ -22,8 +22,8 @@ const BreweryBeersSection: FC<BreweryCommentsSectionProps> = ({ breweryPost }) =
}); });
const { ref: penultimateBeerPostRef } = useInView({ const { ref: penultimateBeerPostRef } = useInView({
/** /**
* When the last beer post comes into view, call setSize from useBeerPostsByBrewery to * When the last beer post comes into view, call setSize from
* load more beer posts. * useBeerPostsByBrewery to load more beer posts.
*/ */
onChange: (visible) => { onChange: (visible) => {
if (!visible || isAtEnd) return; if (!visible || isAtEnd) return;
@@ -60,8 +60,9 @@ const BreweryBeersSection: FC<BreweryCommentsSectionProps> = ({ breweryPost }) =
const isPenultimateBeerPost = index === beerPosts.length - 2; const isPenultimateBeerPost = index === beerPosts.length - 2;
/** /**
* Attach a ref to the second last beer post in the list. When it comes * Attach a ref to the second last beer post in the list.
* into view, the component will call setSize to load more beer posts. * When it comes into view, the component will call
* setSize to load more beer posts.
*/ */
return ( return (
@@ -90,8 +91,8 @@ const BreweryBeersSection: FC<BreweryCommentsSectionProps> = ({ breweryPost }) =
{ {
/** /**
* If there are more beer posts to load, show a loading component with a * If there are more beer posts to load, show a loading component
* skeleton loader and a loading spinner. * with a skeleton loader and a loading spinner.
*/ */
!!isLoadingMore && !isAtEnd && ( !!isLoadingMore && !isAtEnd && (
<BeerRecommendationLoadingComponent length={PAGE_SIZE} /> <BeerRecommendationLoadingComponent length={PAGE_SIZE} />

View File

@@ -0,0 +1,60 @@
import useBreweryPostComments from '@/hooks/data-fetching/brewery-comments/useBreweryPostComments';
import BreweryPostQueryResult from '@/services/BreweryPost/types/BreweryPostQueryResult';
import CreateCommentValidationSchema from '@/services/types/CommentSchema/CreateCommentValidationSchema';
import { zodResolver } from '@hookform/resolvers/zod';
import { FC } from 'react';
import { useForm, SubmitHandler } from 'react-hook-form';
import toast from 'react-hot-toast';
import { z } from 'zod';
import sendCreateBreweryCommentRequest from '@/requests/BreweryComment/sendCreateBreweryCommentRequest';
import createErrorToast from '@/util/createErrorToast';
import CommentForm from '../ui/CommentForm';
interface BreweryCommentFormProps {
breweryPost: z.infer<typeof BreweryPostQueryResult>;
mutate: ReturnType<typeof useBreweryPostComments>['mutate'];
}
const BreweryCommentForm: FC<BreweryCommentFormProps> = ({ breweryPost, mutate }) => {
const { register, handleSubmit, formState, watch, reset, setValue } = useForm<
z.infer<typeof CreateCommentValidationSchema>
>({
defaultValues: { rating: 0 },
resolver: zodResolver(CreateCommentValidationSchema),
});
const onSubmit: SubmitHandler<z.infer<typeof CreateCommentValidationSchema>> = async (
data,
) => {
const loadingToast = toast.loading('Posting a new comment...');
try {
await sendCreateBreweryCommentRequest({
content: data.content,
rating: data.rating,
breweryPostId: breweryPost.id,
});
reset();
toast.remove(loadingToast);
toast.success('Comment posted successfully.');
await mutate();
} catch (error) {
await mutate();
toast.remove(loadingToast);
createErrorToast(error);
reset();
}
};
return (
<CommentForm
handleSubmit={handleSubmit}
onSubmit={onSubmit}
watch={watch}
setValue={setValue}
formState={formState}
register={register}
/>
);
};
export default BreweryCommentForm;

View File

@@ -3,93 +3,16 @@ import BreweryPostQueryResult from '@/services/BreweryPost/types/BreweryPostQuer
import { FC, MutableRefObject, useContext, useRef } from 'react'; import { FC, MutableRefObject, useContext, useRef } from 'react';
import { z } from 'zod'; import { z } from 'zod';
import CreateCommentValidationSchema from '@/services/types/CommentSchema/CreateCommentValidationSchema'; import CreateCommentValidationSchema from '@/services/types/CommentSchema/CreateCommentValidationSchema';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm, SubmitHandler } from 'react-hook-form';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import CommentQueryResult from '@/services/types/CommentSchema/CommentQueryResult';
import useBreweryPostComments from '@/hooks/data-fetching/brewery-comments/useBreweryPostComments'; import useBreweryPostComments from '@/hooks/data-fetching/brewery-comments/useBreweryPostComments';
import ToastContext from '@/contexts/ToastContext';
import LoadingComponent from '../BeerById/LoadingComponent'; import LoadingComponent from '../BeerById/LoadingComponent';
import CommentsComponent from '../ui/CommentsComponent'; import CommentsComponent from '../ui/CommentsComponent';
import CommentForm from '../ui/CommentForm'; import BreweryCommentForm from './BreweryCommentForm';
interface BreweryBeerSectionProps { interface BreweryBeerSectionProps {
breweryPost: z.infer<typeof BreweryPostQueryResult>; breweryPost: z.infer<typeof BreweryPostQueryResult>;
} }
interface BreweryCommentFormProps {
breweryPost: z.infer<typeof BreweryPostQueryResult>;
mutate: ReturnType<typeof useBreweryPostComments>['mutate'];
}
const BreweryCommentValidationSchemaWithId = CreateCommentValidationSchema.extend({
breweryPostId: z.string(),
});
const sendCreateBreweryCommentRequest = async ({
content,
rating,
breweryPostId,
}: z.infer<typeof BreweryCommentValidationSchemaWithId>) => {
const response = await fetch(`/api/breweries/${breweryPostId}/comments`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ content, rating }),
});
if (!response.ok) {
throw new Error(response.statusText);
}
const data = await response.json();
const parsedResponse = APIResponseValidationSchema.safeParse(data);
if (!parsedResponse.success) {
throw new Error('Invalid API response');
}
const parsedPayload = CommentQueryResult.safeParse(parsedResponse.data.payload);
if (!parsedPayload.success) {
throw new Error('Invalid API response payload');
}
return parsedPayload.data;
};
const BreweryCommentForm: FC<BreweryCommentFormProps> = ({ breweryPost, mutate }) => {
const { register, handleSubmit, formState, watch, reset, setValue } = useForm<
z.infer<typeof CreateCommentValidationSchema>
>({
defaultValues: { rating: 0 },
resolver: zodResolver(CreateCommentValidationSchema),
});
const { toast } = useContext(ToastContext);
const onSubmit: SubmitHandler<z.infer<typeof CreateCommentValidationSchema>> = async (
data,
) => {
await sendCreateBreweryCommentRequest({
content: data.content,
rating: data.rating,
breweryPostId: breweryPost.id,
});
await mutate();
toast.loading('Created new comment.');
reset();
};
return (
<CommentForm
handleSubmit={handleSubmit}
onSubmit={onSubmit}
watch={watch}
setValue={setValue}
formState={formState}
register={register}
/>
);
};
const BreweryCommentsSection: FC<BreweryBeerSectionProps> = ({ breweryPost }) => { const BreweryCommentsSection: FC<BreweryBeerSectionProps> = ({ breweryPost }) => {
const { user } = useContext(UserContext); const { user } = useContext(UserContext);

View File

@@ -1,6 +1,6 @@
import useCheckIfUserLikesBreweryPost from '@/hooks/data-fetching/brewery-likes/useCheckIfUserLikesBreweryPost'; import useCheckIfUserLikesBreweryPost from '@/hooks/data-fetching/brewery-likes/useCheckIfUserLikesBreweryPost';
import useGetBreweryPostLikeCount from '@/hooks/data-fetching/brewery-likes/useGetBreweryPostLikeCount'; import useGetBreweryPostLikeCount from '@/hooks/data-fetching/brewery-likes/useGetBreweryPostLikeCount';
import sendBreweryPostLikeRequest from '@/requests/sendBreweryPostLikeRequest'; import sendBreweryPostLikeRequest from '@/requests/BreweryPostLike/sendBreweryPostLikeRequest';
import { FC, useState } from 'react'; import { FC, useState } from 'react';
import LikeButton from '../ui/LikeButton'; import LikeButton from '../ui/LikeButton';

View File

@@ -1,15 +1,17 @@
import { zodResolver } from '@hookform/resolvers/zod'; import { zodResolver } from '@hookform/resolvers/zod';
import { BeerType } from '@prisma/client'; import { BeerType } from '@prisma/client';
import router from 'next/router'; import router from 'next/router';
import { FunctionComponent, useState } from 'react'; import { FunctionComponent } from 'react';
import { useForm, SubmitHandler, FieldError } from 'react-hook-form'; import { useForm, SubmitHandler, FieldError } from 'react-hook-form';
import { z } from 'zod'; import { z } from 'zod';
import BreweryPostQueryResult from '@/services/BreweryPost/types/BreweryPostQueryResult'; import BreweryPostQueryResult from '@/services/BreweryPost/types/BreweryPostQueryResult';
import CreateBeerPostValidationSchema from '@/services/BeerPost/schema/CreateBeerPostValidationSchema'; import CreateBeerPostValidationSchema from '@/services/BeerPost/schema/CreateBeerPostValidationSchema';
import sendCreateBeerPostRequest from '@/requests/sendCreateBeerPostRequest'; import sendCreateBeerPostRequest from '@/requests/BeerPost/sendCreateBeerPostRequest';
import UploadImageValidationSchema from '@/services/types/ImageSchema/UploadImageValidationSchema'; import UploadImageValidationSchema from '@/services/types/ImageSchema/UploadImageValidationSchema';
import sendUploadBeerImagesRequest from '@/requests/sendUploadBeerImageRequest'; import sendUploadBeerImagesRequest from '@/requests/BeerImage/sendUploadBeerImageRequest';
import ErrorAlert from './ui/alerts/ErrorAlert';
import toast from 'react-hot-toast';
import Button from './ui/forms/Button'; import Button from './ui/forms/Button';
import FormError from './ui/forms/FormError'; import FormError from './ui/forms/FormError';
import FormInfo from './ui/forms/FormInfo'; import FormInfo from './ui/forms/FormInfo';
@@ -40,7 +42,6 @@ const CreateBeerPostForm: FunctionComponent<BeerFormProps> = ({
}); });
const { errors, isSubmitting } = formState; const { errors, isSubmitting } = formState;
const [error, setError] = useState('');
const onSubmit: SubmitHandler< const onSubmit: SubmitHandler<
z.infer<typeof CreateBeerPostWithImagesValidationSchema> z.infer<typeof CreateBeerPostWithImagesValidationSchema>
@@ -52,19 +53,17 @@ const CreateBeerPostForm: FunctionComponent<BeerFormProps> = ({
try { try {
const response = await sendCreateBeerPostRequest(data); const response = await sendCreateBeerPostRequest(data);
await sendUploadBeerImagesRequest({ beerPost: response, images: data.images }); await sendUploadBeerImagesRequest({ beerPost: response, images: data.images });
router.push(`/beers/${response.id}`); await router.push(`/beers/${response.id}`);
toast.success('Created beer post.');
} catch (e) { } catch (e) {
if (!(e instanceof Error)) { const errorMessage = e instanceof Error ? e.message : 'Something went wrong.';
setError('Something went wrong');
return; toast.error(errorMessage);
}
setError(e.message);
} }
}; };
return ( return (
<form className="form-control" onSubmit={handleSubmit(onSubmit)}> <form className="form-control" onSubmit={handleSubmit(onSubmit)}>
<div>{error && <ErrorAlert error={error} setError={setError} />}</div>
<FormInfo> <FormInfo>
<FormLabel htmlFor="name">Name</FormLabel> <FormLabel htmlFor="name">Name</FormLabel>
<FormError>{errors.name?.message}</FormError> <FormError>{errors.name?.message}</FormError>

View File

@@ -1,12 +1,14 @@
import sendEditBeerPostRequest from '@/requests/sendEditBeerPostRequest'; import { FC } from 'react';
import EditBeerPostValidationSchema from '@/services/BeerPost/schema/EditBeerPostValidationSchema';
import { zodResolver } from '@hookform/resolvers/zod';
import { useRouter } from 'next/router'; import { useRouter } from 'next/router';
import { FC, useState } from 'react'; import toast from 'react-hot-toast';
import { useForm, SubmitHandler } from 'react-hook-form';
import { z } from 'zod'; import { z } from 'zod';
import ErrorAlert from './ui/alerts/ErrorAlert'; import { useForm, SubmitHandler } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import deleteBeerPostRequest from '@/requests/BeerPost/deleteBeerPostRequest';
import EditBeerPostValidationSchema from '@/services/BeerPost/schema/EditBeerPostValidationSchema';
import sendEditBeerPostRequest from '@/requests/BeerPost/sendEditBeerPostRequest';
import Button from './ui/forms/Button'; import Button from './ui/forms/Button';
import FormError from './ui/forms/FormError'; import FormError from './ui/forms/FormError';
import FormInfo from './ui/forms/FormInfo'; import FormInfo from './ui/forms/FormInfo';
@@ -23,54 +25,36 @@ interface EditBeerPostFormProps {
const EditBeerPostForm: FC<EditBeerPostFormProps> = ({ previousValues }) => { const EditBeerPostForm: FC<EditBeerPostFormProps> = ({ previousValues }) => {
const router = useRouter(); const router = useRouter();
const { const { register, handleSubmit, formState } = useForm<EditBeerPostSchema>({
register,
handleSubmit,
formState: { errors },
} = useForm<EditBeerPostSchema>({
resolver: zodResolver(EditBeerPostValidationSchema), resolver: zodResolver(EditBeerPostValidationSchema),
defaultValues: previousValues, defaultValues: previousValues,
}); });
const [error, setError] = useState(''); const { isSubmitting, errors } = formState;
const [isSubmitting, setIsSubmitting] = useState(false);
const onSubmit: SubmitHandler<EditBeerPostSchema> = async (data) => { const onSubmit: SubmitHandler<EditBeerPostSchema> = async (data) => {
try { try {
setIsSubmitting(true);
await sendEditBeerPostRequest(data); await sendEditBeerPostRequest(data);
router.push(`/beers/${data.id}`); await router.push(`/beers/${data.id}`);
toast.success('Edited beer post.');
} catch (e) { } catch (e) {
setIsSubmitting(false); const errorMessage = e instanceof Error ? e.message : 'Something went wrong.';
if (!(e instanceof Error)) { toast.error(errorMessage);
setError('Something went wrong'); await router.push(`/beers/${data.id}`);
return;
}
setError(e.message);
} }
}; };
const onDelete = async () => { const onDelete = async () => {
try { try {
const response = await fetch(`/api/beers/${previousValues.id}`, { await deleteBeerPostRequest(previousValues.id);
method: 'DELETE', await router.push('/beers');
});
if (response.status === 200) {
router.push('/beers');
}
} catch (e) { } catch (e) {
if (!(e instanceof Error)) { const errorMessage = e instanceof Error ? e.message : 'Something went wrong.';
setError('Something went wrong'); toast.error(errorMessage);
return; await router.push(`/beers`);
}
setError(e.message);
} }
}; };
return ( return (
<form className="form-control" onSubmit={handleSubmit(onSubmit)}> <form className="form-control" onSubmit={handleSubmit(onSubmit)}>
<div className="mb-5">
{error && <ErrorAlert error={error} setError={setError} />}
</div>
<FormInfo> <FormInfo>
<FormLabel htmlFor="name">Name</FormLabel> <FormLabel htmlFor="name">Name</FormLabel>
<FormError>{errors.name?.message}</FormError> <FormError>{errors.name?.message}</FormError>

View File

@@ -1,13 +1,14 @@
import sendLoginUserRequest from '@/requests/sendLoginUserRequest'; import sendLoginUserRequest from '@/requests/User/sendLoginUserRequest';
import LoginValidationSchema from '@/services/User/schema/LoginValidationSchema'; import LoginValidationSchema from '@/services/User/schema/LoginValidationSchema';
import { zodResolver } from '@hookform/resolvers/zod'; import { zodResolver } from '@hookform/resolvers/zod';
import { useRouter } from 'next/router'; import { useRouter } from 'next/router';
import { useContext, useState } from 'react'; import { useContext } from 'react';
import { useForm, SubmitHandler } from 'react-hook-form'; import { useForm, SubmitHandler } from 'react-hook-form';
import { z } from 'zod'; import { z } from 'zod';
import UserContext from '@/contexts/UserContext'; import UserContext from '@/contexts/UserContext';
import ToastContext from '@/contexts/ToastContext'; import toast from 'react-hot-toast';
import ErrorAlert from '../ui/alerts/ErrorAlert';
import createErrorToast from '@/util/createErrorToast';
import FormError from '../ui/forms/FormError'; import FormError from '../ui/forms/FormError';
import FormInfo from '../ui/forms/FormInfo'; import FormInfo from '../ui/forms/FormInfo';
import FormLabel from '../ui/forms/FormLabel'; import FormLabel from '../ui/forms/FormLabel';
@@ -28,24 +29,21 @@ const LoginForm = () => {
const { errors } = formState; const { errors } = formState;
const [responseError, setResponseError] = useState<string>('');
const { mutate } = useContext(UserContext); const { mutate } = useContext(UserContext);
const { toast } = useContext(ToastContext);
const onSubmit: SubmitHandler<LoginT> = async (data) => { const onSubmit: SubmitHandler<LoginT> = async (data) => {
const loadingToast = toast.loading('Logging in...');
try { try {
const id = toast.loading('Logging in.');
await sendLoginUserRequest(data); await sendLoginUserRequest(data);
await mutate!(); await mutate!();
toast.remove(loadingToast);
toast.success('Logged in!');
await router.push(`/user/current`); await router.push(`/user/current`);
toast.remove(id);
} catch (error) { } catch (error) {
if (error instanceof Error) { toast.remove(loadingToast);
setResponseError(error.message); createErrorToast(error);
reset(); reset();
} }
}
}; };
return ( return (
@@ -82,7 +80,6 @@ const LoginForm = () => {
</FormSegment> </FormSegment>
</div> </div>
{responseError && <ErrorAlert error={responseError} setError={setResponseError} />}
<div className="w-full"> <div className="w-full">
<Button type="submit" isSubmitting={formState.isSubmitting}> <Button type="submit" isSubmitting={formState.isSubmitting}>
Login Login

View File

@@ -1,12 +1,14 @@
import sendRegisterUserRequest from '@/requests/sendRegisterUserRequest'; import sendRegisterUserRequest from '@/requests/User/sendRegisterUserRequest';
import { CreateUserValidationSchemaWithUsernameAndEmailCheck } from '@/services/User/schema/CreateUserValidationSchemas'; import { CreateUserValidationSchemaWithUsernameAndEmailCheck } from '@/services/User/schema/CreateUserValidationSchemas';
import { zodResolver } from '@hookform/resolvers/zod'; import { zodResolver } from '@hookform/resolvers/zod';
import { useRouter } from 'next/router'; import { useRouter } from 'next/router';
import { FC, useState } from 'react'; import { FC } from 'react';
import { useForm } from 'react-hook-form'; import { useForm } from 'react-hook-form';
import { z } from 'zod'; import { z } from 'zod';
import ErrorAlert from './ui/alerts/ErrorAlert';
import createErrorToast from '@/util/createErrorToast';
import toast from 'react-hot-toast';
import Button from './ui/forms/Button'; import Button from './ui/forms/Button';
import FormError from './ui/forms/FormError'; import FormError from './ui/forms/FormError';
import FormInfo from './ui/forms/FormInfo'; import FormInfo from './ui/forms/FormInfo';
@@ -21,7 +23,6 @@ const RegisterUserForm: FC = () => {
>({ resolver: zodResolver(CreateUserValidationSchemaWithUsernameAndEmailCheck) }); >({ resolver: zodResolver(CreateUserValidationSchemaWithUsernameAndEmailCheck) });
const { errors } = formState; const { errors } = formState;
const [serverResponseError, setServerResponseError] = useState('');
const onSubmit = async ( const onSubmit = async (
data: z.infer<typeof CreateUserValidationSchemaWithUsernameAndEmailCheck>, data: z.infer<typeof CreateUserValidationSchemaWithUsernameAndEmailCheck>,
@@ -31,11 +32,10 @@ const RegisterUserForm: FC = () => {
reset(); reset();
router.push('/', undefined, { shallow: true }); router.push('/', undefined, { shallow: true });
} catch (error) { } catch (error) {
setServerResponseError( createErrorToast({
error instanceof Error toast,
? error.message error,
: 'Something went wrong. We could not register your account.', });
);
} }
}; };
return ( return (
@@ -44,11 +44,6 @@ const RegisterUserForm: FC = () => {
noValidate noValidate
onSubmit={handleSubmit(onSubmit)} onSubmit={handleSubmit(onSubmit)}
> >
<div>
{serverResponseError && (
<ErrorAlert error={serverResponseError} setError={setServerResponseError} />
)}
</div>
<div> <div>
<div className="flex flex-col lg:flex-row lg:space-x-3"> <div className="flex flex-col lg:flex-row lg:space-x-3">
<div className="lg:w-[50%]"> <div className="lg:w-[50%]">

View File

@@ -68,8 +68,9 @@ const CommentsComponent: FC<CommentsComponentProps> = ({
const isLastComment = index === comments.length - 1; const isLastComment = index === comments.length - 1;
/** /**
* Attach a ref to the last comment in the list. When it comes into view, the * Attach a ref to the last comment in the list. When it comes
* component will call setSize to load more comments. * into view, the component will call setSize to load more
* comments.
*/ */
return ( return (
<div <div
@@ -88,16 +89,17 @@ const CommentsComponent: FC<CommentsComponentProps> = ({
{ {
/** /**
* If there are more comments to load, show a loading component with a * If there are more comments to load, show a loading component
* skeleton loader and a loading spinner. * with a skeleton loader and a loading spinner.
*/ */
!!isLoadingMore && <LoadingComponent length={pageSize} /> !!isLoadingMore && <LoadingComponent length={pageSize} />
} }
{ {
/** /**
* If the user has scrolled to the end of the comments, show a button that * If the user has scrolled to the end of the comments, show a
* will scroll them back to the top of the comments section. * button that will scroll them back to the top of the comments
* section.
*/ */
!!isAtEnd && ( !!isAtEnd && (
<div className="flex h-20 items-center justify-center text-center"> <div className="flex h-20 items-center justify-center text-center">

View File

@@ -1,4 +1,3 @@
import ToastContext from '@/contexts/ToastContext';
import { FC, ReactNode } from 'react'; import { FC, ReactNode } from 'react';
import toast, { Toast, Toaster, resolveValue } from 'react-hot-toast'; import toast, { Toast, Toaster, resolveValue } from 'react-hot-toast';
import { FaTimes } from 'react-icons/fa'; import { FaTimes } from 'react-icons/fa';
@@ -22,29 +21,31 @@ const toastToClassName = (toastType: Toast['type']) => {
const CustomToast: FC<{ children: ReactNode }> = ({ children }) => { const CustomToast: FC<{ children: ReactNode }> = ({ children }) => {
return ( return (
<ToastContext.Provider value={{ toast }}> <>
<Toaster> <Toaster position="bottom-center">
{(t) => { {(t) => {
const alertType = toastToClassName(t.type); const alertType = toastToClassName(t.type);
return ( return (
<div className="flex w-full items-center justify-center">
<div <div
className={`alert ${alertType} w-11/12 flex-row items-center py-[0.5rem] shadow-lg animate-in fade-in duration-200 lg:w-6/12`} className={`alert ${alertType} w-11/12 flex-row items-center shadow-lg animate-in fade-in duration-200 lg:w-6/12`}
> >
<div>{resolveValue(t.message, t)}</div> <p>{resolveValue(t.message, t)}</p>
{t.type !== 'loading' && (
<div>
<button <button
className="btn-ghost btn-circle btn" className="btn-ghost btn-xs btn-circle btn"
onClick={() => toast.dismiss(t.id)} onClick={() => toast.dismiss(t.id)}
> >
<FaTimes /> <FaTimes />
</button> </button>
</div> </div>
)}
</div> </div>
); );
}} }}
</Toaster> </Toaster>
{children} {children}
</ToastContext.Provider> </>
); );
}; };
export default CustomToast; export default CustomToast;

View File

@@ -1,32 +0,0 @@
import { Dispatch, FC, SetStateAction } from 'react';
import { FiAlertTriangle } from 'react-icons/fi';
interface ErrorAlertProps {
error: string;
setError: Dispatch<SetStateAction<string>>;
}
const ErrorAlert: FC<ErrorAlertProps> = ({ error, setError }) => {
return (
<div className="alert alert-error flex-row shadow-lg">
<div className="space-x-1">
<FiAlertTriangle className="h-6 w-6" />
<span>{error}</span>
</div>
<div className="flex-none">
<button
className="btn-ghost btn-sm btn"
type="button"
onClick={() => {
setError('');
}}
>
OK
</button>
</div>
</div>
);
};
export default ErrorAlert;

View File

@@ -1,8 +0,0 @@
import { createContext } from 'react';
import toast from 'react-hot-toast';
const ToastContext = createContext<{
toast: typeof toast;
}>({ toast });
export default ToastContext;

View File

@@ -18,8 +18,9 @@ import { useState, useEffect } from 'react';
*/ */
const useMediaQuery = (query: `(${string})`) => { const useMediaQuery = (query: `(${string})`) => {
/** /**
* Initialize the matches state variable to false. This is updated whenever the viewport * Initialize the matches state variable to false. This is updated whenever the
* size changes (i.e. when the component is mounted and when the window is resized) * viewport size changes (i.e. when the component is mounted and when the window is
* resized)
*/ */
const [matches, setMatches] = useState(false); const [matches, setMatches] = useState(false);
@@ -34,8 +35,8 @@ const useMediaQuery = (query: `(${string})`) => {
} }
/** /**
* Add a resize event listener to the window object, and update the `matches` state * Add a resize event listener to the window object, and update the `matches`
* variable whenever the viewport size changes. * state variable whenever the viewport size changes.
*/ */
const listener = () => setMatches(media.matches); const listener = () => setMatches(media.matches);
window.addEventListener('resize', listener); window.addEventListener('resize', listener);

View File

@@ -3,16 +3,14 @@ import { NextPage } from 'next';
import { Tab } from '@headlessui/react'; import { Tab } from '@headlessui/react';
import Head from 'next/head'; import Head from 'next/head';
import GetUserSchema from '@/services/User/schema/GetUserSchema';
import { z } from 'zod';
import DBClient from '@/prisma/DBClient';
import AccountInfo from '@/components/Account/AccountInfo'; import AccountInfo from '@/components/Account/AccountInfo';
import { useContext } from 'react';
import UserContext from '@/contexts/UserContext';
interface AccountPageProps { const AccountPage: NextPage = () => {
user: z.infer<typeof GetUserSchema>; const { user } = useContext(UserContext);
} if (!user) return null;
const AccountPage: NextPage<AccountPageProps> = ({ user }) => {
return ( return (
<> <>
<Head> <Head>
@@ -30,7 +28,7 @@ const AccountPage: NextPage<AccountPageProps> = ({ user }) => {
</div> </div>
<div className="flex flex-col items-center space-y-1"> <div className="flex flex-col items-center space-y-1">
<p className="text-3xl font-bold">Hello, {user.username}!</p> <p className="text-3xl font-bold">Hello, {user!.username}!</p>
<p className="text-lg">Welcome to your account page.</p> <p className="text-lg">Welcome to your account page.</p>
</div> </div>
</div> </div>
@@ -50,7 +48,7 @@ const AccountPage: NextPage<AccountPageProps> = ({ user }) => {
</Tab.List> </Tab.List>
<Tab.Panels> <Tab.Panels>
<Tab.Panel> <Tab.Panel>
<AccountInfo user={user} /> <AccountInfo />
</Tab.Panel> </Tab.Panel>
<Tab.Panel>Content 3</Tab.Panel> <Tab.Panel>Content 3</Tab.Panel>
</Tab.Panels> </Tab.Panels>
@@ -64,30 +62,4 @@ const AccountPage: NextPage<AccountPageProps> = ({ user }) => {
export default AccountPage; export default AccountPage;
export const getServerSideProps = withPageAuthRequired(async (context, session) => { export const getServerSideProps = withPageAuthRequired();
const { id } = session;
const user: z.infer<typeof GetUserSchema> | null =
await DBClient.instance.user.findUnique({
where: { id },
select: {
username: true,
email: true,
accountIsVerified: true,
firstName: true,
lastName: true,
dateOfBirth: true,
id: true,
createdAt: true,
},
});
if (!user) {
return { redirect: { destination: '/login', permanent: false } };
}
return {
props: {
user: JSON.parse(JSON.stringify(user)),
},
};
});

View File

@@ -0,0 +1,22 @@
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
const deleteBeerPostRequest = async (id: string) => {
const response = await fetch(`/api/beers/${id}`, {
method: 'DELETE',
});
if (!response.ok) {
throw new Error(response.statusText);
}
const json = await response.json();
const parsed = APIResponseValidationSchema.safeParse(json);
if (!parsed.success) {
throw new Error('Could not successfully parse the response.');
}
return parsed;
};
export default deleteBeerPostRequest;

View File

@@ -0,0 +1,39 @@
import CommentQueryResult from '@/services/types/CommentSchema/CommentQueryResult';
import CreateCommentValidationSchema from '@/services/types/CommentSchema/CreateCommentValidationSchema';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { z } from 'zod';
const BreweryCommentValidationSchemaWithId = CreateCommentValidationSchema.extend({
breweryPostId: z.string(),
});
const sendCreateBreweryCommentRequest = async ({
content,
rating,
breweryPostId,
}: z.infer<typeof BreweryCommentValidationSchemaWithId>) => {
const response = await fetch(`/api/breweries/${breweryPostId}/comments`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ content, rating }),
});
if (!response.ok) {
throw new Error(response.statusText);
}
const data = await response.json();
const parsedResponse = APIResponseValidationSchema.safeParse(data);
if (!parsedResponse.success) {
throw new Error('Invalid API response');
}
const parsedPayload = CommentQueryResult.safeParse(parsedResponse.data.payload);
if (!parsedPayload.success) {
throw new Error('Invalid API response payload');
}
return parsedPayload.data;
};
export default sendCreateBreweryCommentRequest;

View File

@@ -0,0 +1,35 @@
import GetUserSchema from '@/services/User/schema/GetUserSchema';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { z } from 'zod';
interface SendEditUserRequestArgs {
user: z.infer<typeof GetUserSchema>;
data: {
username: string;
email: string;
firstName: string;
lastName: string;
};
}
const sendEditUserRequest = async ({ user, data }: SendEditUserRequestArgs) => {
const response = await fetch(`/api/users/${user!.id}/edit`, {
body: JSON.stringify(data),
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
});
if (!response.ok) {
throw new Error(response.statusText);
}
const json = await response.json();
const parsed = APIResponseValidationSchema.safeParse(json);
if (!parsed.success) {
throw new Error('API response validation failed.');
}
return parsed;
};
export default sendEditUserRequest;

View File

@@ -1,7 +1,7 @@
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema'; import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { z } from 'zod'; import { z } from 'zod';
const validateEmail = async (email: string) => { const validateEmailRequest = async (email: string) => {
const response = await fetch(`/api/users/check-email?email=${email}`); const response = await fetch(`/api/users/check-email?email=${email}`);
const json = await response.json(); const json = await response.json();
@@ -22,4 +22,4 @@ const validateEmail = async (email: string) => {
return !parsedPayload.data.emailIsTaken; return !parsedPayload.data.emailIsTaken;
}; };
export default validateEmail; export default validateEmailRequest;

View File

@@ -1,7 +1,7 @@
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema'; import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { z } from 'zod'; import { z } from 'zod';
const validateUsername = async (username: string) => { const validateUsernameRequest = async (username: string) => {
const response = await fetch(`/api/users/check-username?username=${username}`); const response = await fetch(`/api/users/check-username?username=${username}`);
const json = await response.json(); const json = await response.json();
@@ -22,4 +22,4 @@ const validateUsername = async (username: string) => {
return !parsedPayload.data.usernameIsTaken; return !parsedPayload.data.usernameIsTaken;
}; };
export default validateUsername; export default validateUsernameRequest;

View File

@@ -1,15 +0,0 @@
import { BeerPost } from '@prisma/client';
type BeerRecommendationQueryResult = BeerPost & {
brewery: {
id: string;
name: string;
};
beerImages: {
id: string;
alt: string;
url: string;
}[];
};
export default BeerRecommendationQueryResult;

View File

@@ -1,5 +1,5 @@
import validateEmail from '@/requests/valdiateEmail'; import validateEmailRequest from '@/requests/User/validateEmailRequest';
import validateUsername from '@/requests/validateUsername'; import validateUsernameRequest from '@/requests/validateUsernameRequest';
import sub from 'date-fns/sub'; import sub from 'date-fns/sub';
import { z } from 'zod'; import { z } from 'zod';
@@ -55,14 +55,14 @@ export const CreateUserValidationSchemaWithUsernameAndEmailCheck =
email: z email: z
.string() .string()
.email({ message: 'Email must be a valid email address.' }) .email({ message: 'Email must be a valid email address.' })
.refine(async (email) => validateEmail(email), { .refine(async (email) => validateEmailRequest(email), {
message: 'Email is already taken.', message: 'Email is already taken.',
}), }),
username: z username: z
.string() .string()
.min(1, { message: 'Username must not be empty.' }) .min(1, { message: 'Username must not be empty.' })
.max(20, { message: 'Username must be less than 20 characters.' }) .max(20, { message: 'Username must be less than 20 characters.' })
.refine(async (username) => validateUsername(username), { .refine(async (username) => validateUsernameRequest(username), {
message: 'Username is already taken.', message: 'Username is already taken.',
}), }),
}).refine((data) => data.password === data.confirmPassword, { }).refine((data) => data.password === data.confirmPassword, {

View File

@@ -0,0 +1,13 @@
import toast from 'react-hot-toast';
/**
* @param error - The error to display.
*
* Creates a toast message with the error message.
*/
const createErrorToast = (error: unknown) => {
const errorMessage = error instanceof Error ? error.message : 'Something went wrong.';
toast.error(errorMessage);
};
export default createErrorToast;