Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Frontend tokens (#1569)

Dhruv Bhanushalib863e3e4b88e
diff --git a/.env.template b/.env.template
new file mode 100644
index 000000000..57bfac3a2
--- /dev/null
+++ b/.env.template
@@ -0,0 +1,3 @@
+#API_URL=http://127.17.0.1:8000/
+#API_CLIENT_ID=""
+#API_CLIENT_SECRET=""
diff --git a/TESTING_GUIDELINES.md b/TESTING_GUIDELINES.md
index a355d528a..3b282c2ba 100644
--- a/TESTING_GUIDELINES.md
+++ b/TESTING_GUIDELINES.md
@@ -12,10 +12,46 @@ Staging is redeployed everytime we merge to the `main` branch, so if you're look
Once you have the application running, you can visit it in your browser at http://localhost:8443.
-You can also access it from other devices in your same network (like a mobile phone) for additional testing. See the [finding your local IP address](./README.md#finding-your-local-ip-address) section of the README for how to identify the local IP adress Nuxt is served on. Once you have identified your local IP address, you can access the website running on your computer by visiting `https://<local IP>:8443` replacing `<local IP>` (including the brackets) with the value you found using the instructions above in your mobile devices browser.
+You can also access it from other devices in your same network (like a mobile phone) for additional testing. See the [finding your local IP address](./README.md#finding-your-local-ip-address) section of the README for how to identify the local IP adress Nuxt is served on. Once you have identified your local IP address, you can access the website running on your computer by visiting `https://<local IP>:8443` replacing `<local IP>` (including the brackets) with the value you found using the instructions above in your mobile device's browser.
Testing from multiple different devices as often as possible is a great way to contribute to Openverse's frontend development.
+### API Authentication
+
+By default, the application will run using the production API without authentication. This means your local frontend server may be subject to the unauthenticated rate limiting, depending on your testing behavior. There are two ways to solve this:
+
+1. You can change your local Nuxt server to point to a local API server that does not have throttling enabled
+2. You can introduce the environment variables necessary for authenticating with an API
+
+For the first, [run the Openverse API locally](https://github.com/WordPress/openverse-api). Then create a `.env` file by copying the `.env.template` file and update it with the following:
+
+```shell
+API_URL="http://localhost:8000/"
+```
+
+Be sure to remove the leading `#` to uncomment the variable from the copied template.
+
+The run the dev server as usual:
+
+```shell
+pnpm dev
+```
+
+For the second, you'll need to follow [the instructions to set up an OAuth application](https://api.openverse.engineering/v1/#section/Register-and-Authenticate) and then fill in the `API_CLIENT_ID` and `API_CLIENT_SECRET` in the `.env` file copied from `.env.template`. Be sure to remove the leading `#` to uncomment these variables from the copied template.
+
+```shell
+API_CLIENT_ID=""
+API_CLIENT_SECRET=""
+```
+
+Then run the API as usual using `pnpm dev`. Nuxt automatically loads `.env` files into the environment. With these variables in the environment, all requests made by your server will be made using an access token retrieved by the `~/plugins/api-token.server.ts` plugin.
+
+Once the `.env` file is set up, you may run the development build the typical way:
+
+```shell
+pnpm build && pnpm start
+```
+
## Browsers
In addition to testing on multiple devices, we also strive to test on almost all widely used browsers excluding Internet Explorer. Please be ready to regularly test your work and the work of others in Firefox, Chrome, and Safari on a desktop computer. On mobile devices, Mobile Safari on iOS, Firefox for Android and Mobile Chrome on iOS are all important targets for testing as well. A significant amount of web traffic is mobile these days.
diff --git a/nuxt.config.ts b/nuxt.config.ts
index 599917f0a..84eeb1b53 100644
--- a/nuxt.config.ts
+++ b/nuxt.config.ts
@@ -163,14 +163,19 @@ const config: NuxtConfig = {
{ path: '~/components', extensions: ['vue'], pathPrefix: false },
],
plugins: [
- { src: '~/plugins/url-change' },
- { src: '~/plugins/migration-notice' },
- { src: '~/plugins/ua-parse' },
- { src: '~/plugins/focus-visible', mode: 'client' },
+ '~/plugins/url-change.ts',
+ '~/plugins/migration-notice.ts',
+ '~/plugins/ua-parse.ts',
+ '~/plugins/focus-visible.client.ts',
+ '~/plugins/api-token.server.ts',
],
css: ['~/styles/tailwind.css', '~/assets/fonts.css', '~/styles/accent.css'],
head,
- env,
+ env, // TODO: Replace with `publicRuntimeConfig`
+ privateRuntimeConfig: {
+ apiClientId: process.env.API_CLIENT_ID,
+ apiClientSecret: process.env.API_CLIENT_SECRET,
+ },
dev: !isProd,
buildModules: [
'@nuxt/typescript-build',
diff --git a/package.json b/package.json
index 70175d9d7..f9f864084 100644
--- a/package.json
+++ b/package.json
@@ -71,6 +71,7 @@
"@tailwindcss/line-clamp": "^0.3.1",
"@tailwindcss/typography": "^0.5.2",
"@wordpress/is-shallow-equal": "^4.6.0",
+ "async-mutex": "^0.3.2",
"axios": "^0.27.0",
"axios-mock-adapter": "^1.20.0",
"babel-core": "^7.0.0-bridge.0",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 4d34d63ae..9a0c9c654 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -41,6 +41,7 @@ specifiers:
'@vue/runtime-dom': ^3.2.31
'@vue/test-utils': ^1.1.3
'@wordpress/is-shallow-equal': ^4.6.0
+ async-mutex: ^0.3.2
autoprefixer: ^10.4.0
axios: ^0.27.0
axios-mock-adapter: ^1.20.0
@@ -117,6 +118,7 @@ dependencies:
'@tailwindcss/line-clamp': [email protected]
'@tailwindcss/typography': [email protected]
'@wordpress/is-shallow-equal': 4.8.0
+ async-mutex: 0.3.2
axios: 0.27.2
axios-mock-adapter: [email protected]
babel-core: 7.0.0-bridge.0_@[email protected]
@@ -2099,14 +2101,12 @@ packages:
/@cspotcode/source-map-consumer/0.8.0:
resolution: {integrity: sha512-41qniHzTU8yAGbCp04ohlmSrZf8bkf/iJsl3V0dRGsQN/5GFfx+LbCSsCpp2gqrqjTVg/K6O8ycoV35JIwAzAg==}
engines: {node: '>= 12'}
- dev: true
/@cspotcode/source-map-support/0.7.0:
resolution: {integrity: sha512-X4xqRHqN8ACt2aHVe51OxeA2HjbcL4MqFqXkrmQszJ1NOUuUu5u6Vqx/0lZSVNku7velL5FC/s5uEAj1lsBMhA==}
engines: {node: '>=12'}
dependencies:
'@cspotcode/source-map-consumer': 0.8.0
- dev: true
/@csstools/convert-colors/1.4.0:
resolution: {integrity: sha512-5a6wqoJV/xEdbRNKVo6I4hO3VjyDq//8q2f9I6PBAvMesJHFauXDorcNCsr9RzvsZnaWi5NYCcfyqP1QeFHFbw==}
@@ -5754,19 +5754,15 @@ packages:
/@tsconfig/node10/1.0.8:
resolution: {integrity: sha512-6XFfSQmMgq0CFLY1MslA/CPUfhIL919M1rMsa5lP2P097N2Wd1sSX0tx1u4olM16fLNhtHZpRhedZJphNJqmZg==}
- dev: true
/@tsconfig/node12/1.0.9:
resolution: {integrity: sha512-/yBMcem+fbvhSREH+s14YJi18sp7J9jpuhYByADT2rypfajMZZN4WQ6zBGgBKp53NKmqI36wFYDb3yaMPurITw==}
- dev: true
/@tsconfig/node14/1.0.1:
resolution: {integrity: sha512-509r2+yARFfHHE7T6Puu2jjkoycftovhXRqW328PDXTVGKihlb1P8Z9mMZH04ebyajfRY7dedfGynlrFHJUQCg==}
- dev: true
/@tsconfig/node16/1.0.2:
resolution: {integrity: sha512-eZxlbI8GZscaGS7kkc/trHTT5xgrjH3/1n2JDwusC9iahPKWMRvRjJSAN5mCXviuTGQ/lHnhvv8Q1YTpnfz9gA==}
- dev: true
/@types/anymatch/3.0.0:
resolution: {integrity: sha512-qLChUo6yhpQ9k905NwL74GU7TxH+9UODwwQ6ICNI+O6EDMExqH/Cv9NsbmcZ7yC/rRXJ/AHCzfgjsFRY5fKjYw==}
@@ -6707,7 +6703,6 @@ packages:
/@vue/devtools-api/6.1.4:
resolution: {integrity: sha512-IiA0SvDrJEgXvVxjNkHPFfDx6SXw0b/TUkqMcDZWNg9fnCAHbTpoo59YfJ9QLFkwa3raau5vSlRVzMSLDnfdtQ==}
- dev: false
/@vue/reactivity-transform/3.2.31:
resolution: {integrity: sha512-uS4l4z/W7wXdI+Va5pgVxBJ345wyGFKvpPYtdSgvfJfX/x2Ymm6ophQlXXB6acqGHtXuBqNyyO3zVp9b1r0MOA==}
@@ -6722,14 +6717,12 @@ packages:
resolution: {integrity: sha512-HVr0l211gbhpEKYr2hYe7hRsV91uIVGFYNHj73njbARVGHQvIojkImKMaZNDdoDZOIkMsBc9a1sMqR+WZwfSCw==}
dependencies:
'@vue/shared': 3.2.31
- dev: true
/@vue/runtime-core/3.2.31:
resolution: {integrity: sha512-Kcog5XmSY7VHFEMuk4+Gap8gUssYMZ2+w+cmGI6OpZWYOEIcbE0TPzzPHi+8XTzAgx1w/ZxDFcXhZeXN5eKWsA==}
dependencies:
'@vue/reactivity': 3.2.31
'@vue/shared': 3.2.31
- dev: true
/@vue/runtime-dom/3.2.31:
resolution: {integrity: sha512-N+o0sICVLScUjfLG7u9u5XCjvmsexAiPt17GNnaWHJUfsKed5e85/A3SWgKxzlxx2SW/Hw7RQxzxbXez9PtY3g==}
@@ -6737,7 +6730,6 @@ packages:
'@vue/runtime-core': 3.2.31
'@vue/shared': 3.2.31
csstype: 2.6.20
- dev: true
/@vue/shared/3.2.31:
resolution: {integrity: sha512-ymN2pj6zEjiKJZbrf98UM2pfDd6F2H7ksKw7NDt/ZZ1fh5Ei39X5tABugtT03ZRlWd9imccoK0hE8hpjpU7irQ==}
@@ -6929,12 +6921,10 @@ packages:
acorn: 7.4.1
acorn-walk: 7.2.0
xtend: 4.0.2
- dev: true
/acorn-walk/7.2.0:
resolution: {integrity: sha512-OPdCF6GsMIP+Az+aWfAAOEt2/+iVDKE7oy6lJ098aoe59oAmK76qV6Gw60SbZ8jHuG2wH058GF4pLFbYamYrVA==}
engines: {node: '>=0.4.0'}
- dev: true
/acorn-walk/8.2.0:
resolution: {integrity: sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA==}
@@ -6949,13 +6939,11 @@ packages:
resolution: {integrity: sha512-nQyp0o1/mNdbTO1PO6kHkwSrmgZ0MT/jCCpNiwbUjGoRN4dlBhqJtoQuCnEOKzgTVwg0ZWiCoQy6SxMebQVh8A==}
engines: {node: '>=0.4.0'}
hasBin: true
- dev: true
/acorn/8.7.0:
resolution: {integrity: sha512-V/LGr1APy+PXIwKebEWrkZPwoeoF+w1jiOBUmuxuiUIaOHtob8Qc9BTrYo7VuI5fR8tqsy+buA2WFooR5olqvQ==}
engines: {node: '>=0.4.0'}
hasBin: true
- dev: true
/acorn/8.7.1:
resolution: {integrity: sha512-Xx54uLJQZ19lKygFXOWsscKUbsBZW0CPykPhVQdhIeIwrbPmJzqeASDInc8nKBnp/JT6igTs82qPXz069H8I/A==}
@@ -7301,6 +7289,12 @@ packages:
resolution: {integrity: sha512-z/WhQ5FPySLdvREByI2vZiTWwCnF0moMJ1hK9YQwDTHKh6I7/uSckMetoRGb5UBZPC1z0jlw+n/XCgjeH7y1AQ==}
optional: true
+ /async-mutex/0.3.2:
+ resolution: {integrity: sha512-HuTK7E7MT7jZEh1P9GtRW9+aTWiDWWi9InbZ5hjxrnRa39KS4BW04+xLBhYNS2aXhHUIKZSw3gj4Pn1pj+qGAA==}
+ dependencies:
+ tslib: 2.3.1
+ dev: false
+
/async/2.6.4:
resolution: {integrity: sha512-mzo5dfJYwAn29PeiJ0zvwTo04zj8HDJj0Mn8TD7sno7q12prdbnasKJHhkm2c1LgrhlJ0teaea8860oxi51mGA==}
dependencies:
@@ -8082,7 +8076,6 @@ packages:
/camelcase-css/2.0.1:
resolution: {integrity: sha512-QOSvevhslijgYwRx6Rv7zKdMF8lbRmx+uQGx2+vDc+KI/eBnsy9kit5aj23AgGu3pa4t9AgwbnXWqS+iOY+2aA==}
engines: {node: '>= 6'}
- dev: true
/camelcase/5.3.1:
resolution: {integrity: sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==}
@@ -8608,7 +8601,7 @@ packages:
lodash: ^4.17.20
marko: ^3.14.4
mote: ^0.2.0
- mustache: ^4.0.1
+ mustache: ^3.0.0
nunjucks: ^3.2.2
plates: ~0.4.11
pug: ^3.0.0
@@ -8777,7 +8770,7 @@ packages:
lodash: ^4.17.20
marko: ^3.14.4
mote: ^0.2.0
- mustache: ^4.0.1
+ mustache: ^3.0.0
nunjucks: ^3.2.2
plates: ~0.4.11
pug: ^3.0.0
@@ -9420,7 +9413,6 @@ packages:
/csstype/2.6.20:
resolution: {integrity: sha512-/WwNkdXfckNgw6S5R125rrW8ez139lBHWouiBvX8dfMFtcn6V81REDqnH7+CRpRipfYlyU1CmOnOxrmGcFOjeA==}
- dev: true
/csstype/3.0.11:
resolution: {integrity: sha512-sa6P2wJ+CAbgyy4KFssIb/JNMLxFvKF1pCYCSXS8ZMuqZnMsrxqI2E5sPyoTpxoPU/gVZMzr2zjOfg8GIZOMsw==}
@@ -9568,7 +9560,6 @@ packages:
/defined/1.0.0:
resolution: {integrity: sha1-yY2bzvdWdBiOEQlpFRGZ45sfppM=}
- dev: true
/defu/2.0.4:
resolution: {integrity: sha512-G9pEH1UUMxShy6syWk01VQSRVs3CDWtlxtZu7A+NyqjxaCA4gSlWAKDBx6QiUEKezqS8+DUlXLI14Fp05Hmpwg==}
@@ -9657,7 +9648,6 @@ packages:
acorn-node: 1.8.2
defined: 1.0.0
minimist: 1.2.5
- dev: true
/devalue/2.0.1:
resolution: {integrity: sha512-I2TiqT5iWBEyB8GRfTDP0hiLZ0YeDJZ+upDxjBfOC2lebO5LezQMv7QvIUTzdb64jQyAKLf1AHADtGN+jw6v8Q==}
@@ -9665,7 +9655,6 @@ packages:
/didyoumean/1.2.2:
resolution: {integrity: sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==}
- dev: true
/diff-sequences/26.6.2:
resolution: {integrity: sha512-Mv/TDa3nZ9sbc5soK+OoA74BsS3mL37yixCvUAQkiuA4Wz6YtwP/K47n2rv2ovzHZvoiQeA5FTQOschKkEwB0Q==}
@@ -9680,7 +9669,6 @@ packages:
/diff/4.0.2:
resolution: {integrity: sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==}
engines: {node: '>=0.3.1'}
- dev: true
/diffie-hellman/5.0.3:
resolution: {integrity: sha512-kqag/Nl+f3GwyK25fhUMYj81BUOrZ9IuJsjIcDE5icNM9FJHAVm3VcUDxdLPoQtTuUylWm6ZIknYJwwaPxsUzg==}
@@ -9704,7 +9692,6 @@ packages:
/dlv/1.1.3:
resolution: {integrity: sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==}
- dev: true
/doctrine/2.1.0:
resolution: {integrity: sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==}
@@ -11270,7 +11257,6 @@ packages:
engines: {node: '>=10.13.0'}
dependencies:
is-glob: 4.0.3
- dev: true
/glob-promise/[email protected]:
resolution: {integrity: sha512-q08RJ6O+eJn+dVanerAndJwIcumgbDdYiUT7zFQl3Wm1xD6fBKtah7H8ZJChj4wP+8C+QfeVy8xautR7rdmKEw==}
@@ -11867,7 +11853,6 @@ packages:
engines: {node: '>=8'}
dependencies:
import-from: 3.0.0
- dev: true
/import-fresh/2.0.0:
resolution: {integrity: sha1-2BNVwVYS04bGH53dOSLUMEgipUY=}
@@ -11896,7 +11881,6 @@ packages:
engines: {node: '>=8'}
dependencies:
resolve-from: 5.0.0
- dev: true
/import-local/3.0.3:
resolution: {integrity: sha512-bE9iaUY3CXH8Cwfan/abDKAxe1KGT9kyGsBPqf6DMK/z0a2OzAsrukeYNgIH6cH5Xr452jb1TUL8rSfCLjZ9uA==}
@@ -13376,7 +13360,6 @@ packages:
/lilconfig/2.0.4:
resolution: {integrity: sha512-bfTIN7lEsiooCocSISTWXkiWJkRqtL9wYtYy+8EK3Y41qh3mpwPU0ycTOgjdY9ErwXCc8QyrQp82bdL0Xkm9yA==}
engines: {node: '>=10'}
- dev: true
/lines-and-columns/1.2.4:
resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==}
@@ -13637,7 +13620,6 @@ packages:
/make-error/1.3.6:
resolution: {integrity: sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==}
- dev: true
/makeerror/1.0.12:
resolution: {integrity: sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg==}
@@ -14453,7 +14435,6 @@ packages:
/object-hash/2.2.0:
resolution: {integrity: sha512-gScRMn0bS5fH+IuwyIFgnh9zBdo4DV+6GhygmWM9HyNJSgS0hScp1f5vjtm7oIIOiT9trXrShAkLFSc2IqKNgw==}
engines: {node: '>= 6'}
- dev: true
/object-inspect/1.12.0:
resolution: {integrity: sha512-Ho2z80bVIvJloH+YzRmpZVQe87+qASmBUKZDWgx9cu+KDrX2ZDH/3tMy+gXbZETVGs2M8YdxObOh7XAtim9Y0g==}
@@ -14959,7 +14940,6 @@ packages:
typescript: 4.6.2
vue: 2.6.14
- dev: false
/pirates/4.0.4:
resolution: {integrity: sha512-ZIrVPH+A52Dw84R0L3/VS9Op04PuQ2SEoJL6bkshmiTic/HldyW9Tf7oH5mhJZBK7NmDx27vSMrYEXPXclpDKw==}
@@ -15324,7 +15304,6 @@ packages:
dependencies:
camelcase-css: 2.0.1
postcss: 8.4.12
- dev: true
/postcss-lab-function/2.0.1:
resolution: {integrity: sha512-whLy1IeZKY+3fYdqQFuDBf8Auw+qFuVnChWjmxm/UhHWqNHZx+B99EwxTvGYmUBqe3Fjxs4L1BoZTJmPu6usVg==}
@@ -15356,7 +15335,6 @@ packages:
lilconfig: 2.0.4
ts-node: 10.7.0_cbygeln5s5sjlseyk3kbidkfny
yaml: 1.10.2
- dev: true
/postcss-loader/3.0.0:
resolution: {integrity: sha512-cLWoDEY5OwHcAjDnkyRQzAXfs2jrKjXpO/HQFcc5b5u/r7aa471wdmChmwfnv7x2u840iat/wi0lQ5nbRgSkUA==}
@@ -15548,7 +15526,6 @@ packages:
dependencies:
postcss: 8.4.12
postcss-selector-parser: 6.0.9
- dev: true
/postcss-nesting/7.0.1:
resolution: {integrity: sha512-FrorPb0H3nuVq0Sff7W2rnc3SmIcruVC6YwpcS+k687VxyxO33iE1amna7wHuRVzM8vfiYofXSBHNAZ3QhLvYg==}
@@ -16317,7 +16294,6 @@ packages:
/quick-lru/5.1.1:
resolution: {integrity: sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==}
engines: {node: '>=10'}
- dev: true
/ramda/0.21.0:
resolution: {integrity: sha1-oAGr7bP/YQd9T/HVd9RN536NCjU=}
@@ -17062,7 +17038,6 @@ packages:
/resolve-from/5.0.0:
resolution: {integrity: sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==}
engines: {node: '>=8'}
- dev: true
/resolve-path/1.4.0:
resolution: {integrity: sha1-xL2p9e+y/OZSR4c6s2u02DT+Fvc=}
@@ -18205,7 +18180,6 @@ packages:
resolve: 1.22.0
transitivePeerDependencies:
- ts-node
- dev: true
/talkback/3.0.1:
resolution: {integrity: sha512-2/mBW8vhcNw3JN5q8Pvq9QLdd3seks859EVabmRpSev2cyCPX4A7eU87jUnlBDOyXYdXPAflJ7cRkyTHmSKNGQ==}
@@ -18559,7 +18533,6 @@ packages:
typescript: 4.6.2
v8-compile-cache-lib: 3.0.0
yn: 3.1.1
- dev: true
resolution: {integrity: sha512-csd+vJOb/gkzvcCHgTGSChYpy5f1/XKNsmvBGO4JXS+z1v2HobugDz4s1IeFXM3wZB44uczs+eazB5Q/ccdhQw==}
@@ -18672,7 +18645,6 @@ packages:
resolution: {integrity: sha512-HM/hFigTBHZhLXshn9sN37H085+hQGeJHJ/X7LpBWLID/fbc2acUMfU+lGD98X81sKP+pFa9f0DZmCwB9GnbAg==}
engines: {node: '>=4.2.0'}
hasBin: true
- dev: true
/ua-parser-js/0.7.31:
resolution: {integrity: sha512-qLK/Xe9E2uzmYI3qLeOmI0tEOt+TBBQyUIAh4aAgU05FVYzeZrKUdkAZfBNVGRaHVgV0TDkdEngJSw/SyQchkQ==}
@@ -19083,7 +19055,6 @@ packages:
/v8-compile-cache-lib/3.0.0:
resolution: {integrity: sha512-mpSYqfsFvASnSn5qMiwrr4VKfumbPyONLCOPmsR3A6pTY/r0+tSaVbgPWSAIuzbk3lCTa+FForeTiO+wBQGkjA==}
- dev: true
/v8-compile-cache/2.3.0:
resolution: {integrity: sha512-l8lCEmLcLYZh4nbunNZvQCJc5pv7+RCwa8q/LdUx8u7lsWvPDKmpodJAJNwkAhJC//dFY48KuIEmjtd4RViDrA==}
@@ -19489,7 +19460,6 @@ packages:
/vue/2.6.14:
resolution: {integrity: sha512-x2284lgYvjOMj3Za7kqzRcUSxBboHqtgRE2zlos1qWaOye5yUmHn42LB1250NJBLRwEcdrB0JRwyPTEPhfQjiQ==}
- dev: false
resolution: {integrity: sha512-ETW44IqCgBpVomy520DT5jf8n0zoCac+sxWnn+hMe/CzaSejb/eVw2YToiXYX+Ex/AuHHia28vWTq4goAexFbw==}
@@ -20015,7 +19985,6 @@ packages:
/yn/3.1.1:
resolution: {integrity: sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==}
engines: {node: '>=6'}
- dev: true
/yocto-queue/0.1.0:
resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==}
diff --git a/src/data/api-service.ts b/src/data/api-service.ts
index 75a73e8aa..0d4ba1937 100644
--- a/src/data/api-service.ts
+++ b/src/data/api-service.ts
@@ -1,4 +1,4 @@
-import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
+import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { warn } from '~/utils/console'
import { AUDIO, IMAGE } from '~/constants/media'
@@ -15,6 +15,7 @@ export const getResourceSlug = (resource: string): string => {
const slug = { [AUDIO]: 'audio', [IMAGE]: 'images' }[resource] ?? resource
return `${slug}/`
}
+
/**
* @param errorCondition - if true, the `message` warning is logged in the console
* @param message - message to display if there is an error in request
@@ -34,14 +35,62 @@ Please check the url: ${config.baseURL}${config.url}`
}
/**
- *
- * @param baseUrl - the optional base url to override the `env.apiUrl`
+ * the list of options that can be passed when instantiating a new API service.
*/
-export const createApiService = (baseUrl = process.env.apiUrl) => {
- const client = axios.create({
- baseURL: baseUrl,
+export interface ApiServiceConfig {
+ /** to use a different base URL than configured for the environment */
+ baseUrl?: string
+ /** to make authenticated requests to the API */
+ accessToken?: string
+ /** whether to use the `'v1/'` prefix after the base URL */
+ isVersioned?: boolean
+}
+
+/**
+ * the schema of the API service
+ */
+export interface ApiService {
+ client: AxiosInstance
+ query<T = unknown>(
+ resource: string,
+ params: Record<string, string>
+ ): Promise<AxiosResponse<T>>
+ get<T = unknown>(resource: string, slug: string): Promise<AxiosResponse<T>>
+ post<T = unknown>(
+ resource: string,
+ data: Parameters<AxiosInstance['post']>[1],
+ headers?: AxiosRequestConfig['headers']
+ ): Promise<AxiosResponse<T>>
+ update<T = unknown>(
+ resource: string,
+ slug: string,
+ data: Parameters<AxiosInstance['put']>[1],
+ headers: AxiosRequestConfig['headers']
+ ): Promise<AxiosResponse<T>>
+ put<T = unknown>(
+ resource: string,
+ params: AxiosRequestConfig
+ ): Promise<AxiosResponse<T>>
+ delete<T = unknown>(
+ resource: string,
+ slug: string,
+ headers: AxiosRequestConfig['headers']
+ ): Promise<AxiosResponse<T>>
+}
+
+export const createApiService = ({
+ baseUrl = process.env.apiUrl,
+ accessToken = undefined,
+ isVersioned = true,
+}: ApiServiceConfig = {}): ApiService => {
+ const axiosParams: AxiosRequestConfig = {
+ baseURL: isVersioned ? `${baseUrl}v1/` : baseUrl,
timeout: DEFAULT_REQUEST_TIMEOUT,
- })
+ }
+ if (accessToken) {
+ axiosParams.headers = { Authorization: `Bearer ${accessToken}` }
+ }
+ const client = axios.create(axiosParams)
client.interceptors.request.use(function (config) {
validateRequest(
!config.url?.endsWith('/'),
@@ -71,6 +120,8 @@ export const createApiService = (baseUrl = process.env.apiUrl) => {
)
return {
+ client,
+
/**
* @param resource - The endpoint of the resource
* @param params - Url parameter object
@@ -130,10 +181,10 @@ export const createApiService = (baseUrl = process.env.apiUrl) => {
* @param params - Url parameter object
* @returns Response The API response object
*/
- put(
+ put<T = unknown>(
resource: string,
params: AxiosRequestConfig
- ): Promise<AxiosResponse<unknown>> {
+ ): Promise<AxiosResponse<T>> {
return client.put(getResourceSlug(resource), params)
},
@@ -143,15 +194,12 @@ export const createApiService = (baseUrl = process.env.apiUrl) => {
* @param headers - Headers object
* @returns Response The API response object
*/
- delete(
+ delete<T = unknown>(
resource: string,
slug: string,
headers: AxiosRequestConfig['headers']
- ): Promise<AxiosResponse<unknown>> {
+ ): Promise<AxiosResponse<T>> {
return client.delete(`${getResourceSlug(resource)}${slug}`, { headers })
},
}
}
-
-export const VersionedApiService = createApiService(`${process.env.apiUrl}v1/`)
-export const NonversionedApiService = createApiService(`${process.env.apiUrl}`)
diff --git a/src/data/media-provider-service.ts b/src/data/media-provider-service.ts
index 4c7615c83..8ee399c85 100644
--- a/src/data/media-provider-service.ts
+++ b/src/data/media-provider-service.ts
@@ -1,22 +1,35 @@
-import { AUDIO, IMAGE, SupportedMediaType } from '~/constants/media'
-import { VersionedApiService } from '~/data/api-service'
+import { AUDIO, IMAGE } from '~/constants/media'
+import type { AudioDetail, ImageDetail, Media } from '~/models/media'
+import { ApiService, createApiService } from '~/data/api-service'
import type { MediaProvider } from '~/models/media-provider'
-/**
- * Service that calls API to get Media Provider stats
- * @param mediaType - the media type of the provider.
- */
-export const MediaProviderService = (mediaType: SupportedMediaType) => ({
+export class MediaProviderService<T extends Media> {
+ private readonly apiService: ApiService
+ private readonly mediaType: T['frontendMediaType']
+
+ constructor(apiService: ApiService, mediaType: T['frontendMediaType']) {
+ this.apiService = apiService
+ this.mediaType = mediaType
+ }
+
/**
* Implements an endpoint to get audio provider statistics.
* SSR-called
*/
- getProviderStats: async (): Promise<{ data: MediaProvider[] }> => {
- return await VersionedApiService.get(mediaType, 'stats')
- },
-})
+ async getProviderStats(): Promise<{ data: MediaProvider[] }> {
+ return await this.apiService.get(this.mediaType, 'stats')
+ }
+}
-export const providerServices = {
- [AUDIO]: MediaProviderService(AUDIO),
- [IMAGE]: MediaProviderService(IMAGE),
-} as const
+export const initProviderServices = {
+ [AUDIO]: (accessToken?: string) =>
+ new MediaProviderService<AudioDetail>(
+ createApiService({ accessToken }),
+ AUDIO
+ ),
+ [IMAGE]: (accessToken?: string) =>
+ new MediaProviderService<ImageDetail>(
+ createApiService({ accessToken }),
+ IMAGE
+ ),
+}
diff --git a/src/data/media-service.ts b/src/data/media-service.ts
index 3f96c2018..2391954e1 100644
--- a/src/data/media-service.ts
+++ b/src/data/media-service.ts
@@ -1,6 +1,6 @@
import { decodeMediaData } from '~/utils/decode-media-data'
import type { ApiQueryParams } from '~/utils/search-query-transform'
-import { VersionedApiService } from '~/data/api-service'
+import type { ApiService } from '~/data/api-service'
import type { DetailFromMediaType, Media } from '~/models/media'
import type { SupportedMediaType } from '~/constants/media'
@@ -17,9 +17,11 @@ export interface MediaResult<
}
class MediaService<T extends Media> {
+ private readonly apiService: ApiService
private readonly mediaType: T['frontendMediaType']
- constructor(mediaType: T['frontendMediaType']) {
+ constructor(apiService: ApiService, mediaType: T['frontendMediaType']) {
+ this.apiService = apiService
this.mediaType = mediaType
}
@@ -47,7 +49,7 @@ class MediaService<T extends Media> {
async search(
params: ApiQueryParams
): Promise<MediaResult<Record<string, Media>>> {
- const res = await VersionedApiService.query<MediaResult<T[]>>(
+ const res = await this.apiService.query<MediaResult<T[]>>(
this.mediaType,
params as unknown as Record<string, string>
)
@@ -65,7 +67,7 @@ class MediaService<T extends Media> {
`MediaService.getMediaDetail() id parameter required to retrieve ${this.mediaType} details.`
)
}
- const res = await VersionedApiService.get<T>(this.mediaType, id)
+ const res = await this.apiService.get<T>(this.mediaType, id)
return decodeMediaData(res.data, this.mediaType)
}
@@ -81,7 +83,7 @@ class MediaService<T extends Media> {
`MediaService.getRelatedMedia() id parameter required to retrieve related media.`
)
}
- const res = (await VersionedApiService.get(
+ const res = (await this.apiService.get(
this.mediaType,
`${id}/related`
)) as AxiosResponse<MediaResult<DetailFromMediaType<T>[]>>
diff --git a/src/data/report-service.ts b/src/data/report-service.ts
index 18b3fd570..f2cd01d0b 100644
--- a/src/data/report-service.ts
+++ b/src/data/report-service.ts
@@ -1,6 +1,6 @@
import type { MediaType } from '~/constants/media'
import type { ReportReason } from '~/constants/content-report'
-import { getResourceSlug, VersionedApiService } from '~/data/api-service'
+import { createApiService, getResourceSlug } from '~/data/api-service'
interface ReportParams {
mediaType: MediaType
@@ -8,10 +8,12 @@ interface ReportParams {
reason: ReportReason
description?: string
}
+
+const apiService = createApiService()
const ReportService = {
sendReport(params: ReportParams) {
const mediaType = params.mediaType
- return VersionedApiService.post(
+ return apiService.post(
`/${getResourceSlug(mediaType)}${params.identifier}/report`,
params
)
diff --git a/src/pages/search.vue b/src/pages/search.vue
index 0b75e677e..4a94732a5 100644
--- a/src/pages/search.vue
+++ b/src/pages/search.vue
@@ -90,12 +90,6 @@ export default defineComponent({
)
)
- const handleTab = (event: KeyboardEvent, element: string) => {
- if (showScrollButton.value && element !== 'scroll-button') {
- return
- }
- focusIn(document.getElementById('__layout'), Focus.First)
- }
return {
searchGridRef,
isMinScreenMd,
@@ -110,9 +104,6 @@ export default defineComponent({
fetchState,
resultItems,
needsFetching,
- fetchMedia: mediaStore.fetchMedia,
- setSearchStateFromUrl: searchStore.setSearchStateFromUrl,
- handleTab,
}
},
/**
@@ -145,10 +136,23 @@ export default defineComponent({
!isShallowEqualObjects(newRoute.query, oldRoute.query)
) {
const { query, path } = newRoute
- this.setSearchStateFromUrl({ urlQuery: query, path })
+ const searchStore = useSearchStore(this.$nuxt.$pinia)
+ searchStore.setSearchStateFromUrl({ urlQuery: query, path })
await this.fetchMedia()
}
},
},
+ methods: {
+ handleTab(event: KeyboardEvent, element: string) {
+ if (this.showScrollButton.value && element !== 'scroll-button') {
+ return
+ }
+ focusIn(document.getElementById('__layout'), Focus.First)
+ },
+ fetchMedia(...args: unknown[]) {
+ const mediaStore = useMediaStore(this.$pinia)
+ return mediaStore.fetchMedia(...args)
+ },
+ },
})
</script>
diff --git a/src/plugins/api-token.server.ts b/src/plugins/api-token.server.ts
new file mode 100644
index 000000000..871f91d09
--- /dev/null
+++ b/src/plugins/api-token.server.ts
@@ -0,0 +1,193 @@
+import { Mutex, MutexInterface } from 'async-mutex'
+
+import { createApiService } from '~/data/api-service'
+import { log, error } from '~/utils/console'
+
+import type { AxiosError } from 'axios'
+
+import type { Context, Plugin } from '@nuxt/types'
+
+/* Process level state */
+
+export interface Process {
+ tokenData: {
+ accessToken: string
+ accessTokenExpiry: number
+ }
+
+ tokenFetching: Promise<void>
+
+ fetchingMutex: Mutex
+}
+
+export declare let process: NodeJS.Process & Process
+
+/**
+ * Store the plugin's "state" on the `process` to prevent it being
+ * thrown out in dev mode when the plugin's module
+ * is mysteriously reloaded (cache-busted) for each request.
+ */
+process.tokenData = process.tokenData || {
+ accessToken: '', // '' denotes non-existent key
+ accessTokenExpiry: 0, // 0 denotes non-existent key
+}
+
+process.tokenFetching = process.tokenFetching || Promise.resolve()
+
+/* Token refresh logic */
+
+interface TokenResponse {
+ access_token: string
+ expires_in: number
+}
+
+/**
+ * Get the timestamp as the number of seconds from the UNIX epoch.
+ * @returns the UNIX timestamp with a resolution of one second
+ */
+const currTimestamp = (): number => Math.floor(Date.now() / 1e3)
+
+export const expiryThreshold = 5 // seconds
+/**
+ * Check whether an access token does not yet exist or if the existing
+ * access token is set to expire soon.
+ * @returns whether the stored access token is about to expire
+ */
+const isNewTokenNeeded = (): boolean => {
+ if (!process.tokenData.accessToken) {
+ log('isNewTokenNeeded: no existing token found')
+ return true
+ }
+
+ const aboutToExpire =
+ process.tokenData.accessTokenExpiry - expiryThreshold <= currTimestamp()
+ log(`isNewTokenNeeded: aboutToExpire=${aboutToExpire}`)
+ return aboutToExpire
+}
+
+/**
+ * Update `tokenData` with the new access token given the client ID and secret.
+ * @param clientId - the client ID of the application issued by the API
+ * @param clientSecret - the client secret of the application issued by the API
+ */
+const refreshApiAccessToken = async (
+ clientId: string,
+ clientSecret: string
+) => {
+ log('Refreshing access token...')
+ const formData = new URLSearchParams()
+ formData.append('client_id', clientId)
+ formData.append('client_secret', clientSecret)
+ formData.append('grant_type', 'client_credentials')
+
+ const apiService = createApiService()
+ try {
+ const res = await apiService.post<TokenResponse>(
+ 'auth_tokens/token',
+ formData
+ )
+ log('Successfully retrieved API token')
+ process.tokenData.accessToken = res.data.access_token
+ process.tokenData.accessTokenExpiry = currTimestamp() + res.data.expires_in
+ log(
+ `Next token expiry for worker expiry=${process.tokenData.accessTokenExpiry}`
+ )
+ } catch (e) {
+ /**
+ * If an error occurs, serve the current request (and any pending)
+ * anonymously and hope it works. By setting the expiry to 0 we queue
+ * up another token fetch attempt for the next request.
+ */
+ error('Unable to retrieve API token, clearing existing token', e)
+ process.tokenData.accessToken = ''
+ process.tokenData.accessTokenExpiry = 0
+ ;(e as AxiosError).message = `Unable to retrieve API token. ${
+ (e as AxiosError).message
+ }`
+ throw e
+ }
+}
+
+process.fetchingMutex = new Mutex()
+
+/**
+ * Get an async function that always returns a valid, automatically-refreshed
+ * API access token.
+ *
+ * The `fetchingMutex` allows all requests on the same process to understand
+ * whether it's necessary for them to request a token refresh or if another
+ * request has already queued the work. If so, they can just await the process-global
+ * promise that will resolve when the api token data refresh request has resolved.
+ *
+ * @param context - the Nuxt context
+ */
+const getApiAccessToken = async (
+ context: Context
+): Promise<string | undefined> => {
+ const { apiClientId, apiClientSecret } = context.$config
+ if (!(apiClientId || apiClientSecret)) {
+ log('No API client secrets found.')
+ return undefined
+ }
+
+ log('We have client information')
+ let release: MutexInterface.Releaser | undefined = undefined
+
+ // Only request a new token if one is needed _and_ there is
+ // not already another request making the request (represented
+ // by the locked mutex).
+ if (isNewTokenNeeded() && !process.fetchingMutex.isLocked()) {
+ log('acquiring mutex lock')
+ release = await process.fetchingMutex.acquire()
+ log('mutex lock acquired, preparing token refresh request')
+ process.tokenFetching = refreshApiAccessToken(apiClientId, apiClientSecret)
+ }
+
+ try {
+ log('awaiting the fetching of the api token to resolve')
+ await process.tokenFetching
+ log('done waiting for the token, moving on now...')
+ } finally {
+ /**
+ * Releasing must be in a `finally` block otherwise if the
+ * tokenFetching promise raises then the mutex will never
+ * release and subsequent requests will never retry the
+ * refresh.
+ */
+ if (release) {
+ log('releasing mutex')
+ release()
+ log('mutex released')
+ }
+ }
+
+ return process.tokenData.accessToken
+}
+
+/* Plugin */
+
+declare module '@nuxt/types' {
+ interface Context {
+ $openverseApiToken: string
+ }
+}
+
+const apiToken: Plugin = async (context, inject) => {
+ let openverseApiToken: string | undefined
+ try {
+ openverseApiToken = await getApiAccessToken(context)
+
+ if (openverseApiToken) {
+ log('injecting openverseApiToken into request context')
+ } else {
+ log('using empty openverseApiToken')
+ }
+ } catch (e) {
+ // capture the exception but allow the request to continue with anonymous API requests
+ context.$sentry.captureException(e)
+ } finally {
+ inject('openverseApiToken', openverseApiToken || '')
+ }
+}
+
+export default apiToken
diff --git a/src/plugins/focus-visible.ts b/src/plugins/focus-visible.client.ts
similarity index 100%
rename from src/plugins/focus-visible.ts
rename to src/plugins/focus-visible.client.ts
diff --git a/src/stores/media/index.ts b/src/stores/media/index.ts
index 44a8b743a..ed33f8804 100644
--- a/src/stores/media/index.ts
+++ b/src/stores/media/index.ts
@@ -19,7 +19,7 @@ import {
supportedMediaTypes,
isAdditionalSearchType,
} from '~/constants/media'
-import { services } from '~/stores/media/services'
+import { initServices } from '~/stores/media/services'
import { isSearchTypeSupported, useSearchStore } from '~/stores/search'
import { useRelatedMediaStore } from '~/stores/media/related-media'
import { deepFreeze } from '~/utils/deep-freeze'
@@ -346,8 +346,9 @@ export const useMediaStore = defineStore('media', {
}
this._updateFetchState(mediaType, 'start')
try {
- const data = await services[mediaType].search(queryParams)
-
+ const accessToken = this.$nuxt.$openverseApiToken
+ const service = initServices[mediaType](accessToken)
+ const data = await service.search(queryParams)
const mediaCount = data.result_count
let errorMessage
if (!mediaCount) {
diff --git a/src/stores/media/related-media.ts b/src/stores/media/related-media.ts
index 35c2f5a65..cad2c1874 100644
--- a/src/stores/media/related-media.ts
+++ b/src/stores/media/related-media.ts
@@ -5,7 +5,7 @@ import {
initialFetchState,
updateFetchState,
} from '~/composables/use-fetch-state'
-import { services } from '~/stores/media/services'
+import { initServices } from '~/stores/media/services'
import type { Media } from '~/models/media'
import type { SupportedMediaType } from '~/constants/media'
@@ -35,8 +35,10 @@ export const useRelatedMediaStore = defineStore('related-media', {
this.fetchState = updateFetchState(this.fetchState, 'start')
this.media = []
try {
+ const accessToken = this.$nuxt.$openverseApiToken
+ const service = initServices[mediaType](accessToken)
this.media = (
- await services[mediaType].getRelatedMedia<typeof mediaType>(id)
+ await service.getRelatedMedia<typeof mediaType>(id)
).results
this.fetchState = updateFetchState(this.fetchState, 'end')
} catch (error) {
diff --git a/src/stores/media/services.ts b/src/stores/media/services.ts
index 4022a003c..13963f54a 100644
--- a/src/stores/media/services.ts
+++ b/src/stores/media/services.ts
@@ -1,8 +1,11 @@
import { AUDIO, IMAGE } from '~/constants/media'
import MediaService from '~/data/media-service'
import type { AudioDetail, ImageDetail } from '~/models/media'
+import { createApiService } from '~/data/api-service'
-export const services = {
- [AUDIO]: new MediaService<AudioDetail>(AUDIO),
- [IMAGE]: new MediaService<ImageDetail>(IMAGE),
-} as const
+export const initServices = {
+ [AUDIO]: (accessToken?: string) =>
+ new MediaService<AudioDetail>(createApiService({ accessToken }), AUDIO),
+ [IMAGE]: (accessToken?: string) =>
+ new MediaService<ImageDetail>(createApiService({ accessToken }), IMAGE),
+}
diff --git a/src/stores/media/single-result.ts b/src/stores/media/single-result.ts
index 669a6489e..35ab7c355 100644
--- a/src/stores/media/single-result.ts
+++ b/src/stores/media/single-result.ts
@@ -9,7 +9,7 @@ import {
initialFetchState,
updateFetchState,
} from '~/composables/use-fetch-state'
-import { services } from '~/stores/media/services'
+import { initServices } from '~/stores/media/services'
import { useMediaStore } from '~/stores/media/index'
import { useRelatedMediaStore } from '~/stores/media/related-media'
import { useProviderStore } from '~/stores/provider'
@@ -104,9 +104,9 @@ export const useSingleResultStore = defineStore('single-result', {
async fetchMediaItem(type: SupportedMediaType, id: string) {
try {
this._updateFetchState('start')
- this.mediaItem = this._addProviderName(
- await services[type].getMediaDetail(id)
- )
+ const accessToken = this.$nuxt.$openverseApiToken
+ const service = initServices[type](accessToken)
+ this.mediaItem = this._addProviderName(await service.getMediaDetail(id))
this.mediaType = type
this._updateFetchState('end')
diff --git a/src/stores/provider.ts b/src/stores/provider.ts
index d62943e45..8a14770cb 100644
--- a/src/stores/provider.ts
+++ b/src/stores/provider.ts
@@ -11,7 +11,7 @@ import {
supportedMediaTypes,
} from '~/constants/media'
import { warn } from '~/utils/console'
-import { providerServices } from '~/data/media-provider-service'
+import { initProviderServices } from '~/data/media-provider-service'
import type { MediaProvider } from '~/models/media-provider'
import {
FetchState,
@@ -116,7 +116,10 @@ export const useProviderStore = defineStore('provider', {
this._updateFetchState(mediaType, 'start')
let sortedProviders = [] as MediaProvider[]
try {
- const res = await providerServices[mediaType].getProviderStats()
+ const service = initProviderServices[mediaType](
+ this.$nuxt?.$config?.apiAccessToken
+ )
+ const res = await service.getProviderStats()
sortedProviders = sortProviders(res.data)
this._updateFetchState(mediaType, 'end')
} catch (error: unknown) {
diff --git a/src/utils/console.ts b/src/utils/console.ts
index 253f51f64..165b63dce 100644
--- a/src/utils/console.ts
+++ b/src/utils/console.ts
@@ -1,7 +1,7 @@
-import { isProd } from '~/utils/node-env'
+import { isProd, isClient } from '~/utils/node-env'
export const getLogger = (level: 'log' | 'warn' | 'error') =>
- isProd
+ isProd && isClient
? () => {
// do nothing
}
@@ -9,3 +9,4 @@ export const getLogger = (level: 'log' | 'warn' | 'error') =>
export const warn = getLogger('warn')
export const log = getLogger('log')
+export const error = getLogger('error')
diff --git a/src/utils/node-env.ts b/src/utils/node-env.ts
index 3a14c9ae3..4c4e429ae 100644
--- a/src/utils/node-env.ts
+++ b/src/utils/node-env.ts
@@ -1,3 +1,5 @@
export const isDev: boolean = process.env.NODE_ENV === 'development'
export const isTest: boolean = process.env.NODE_ENV === 'test'
export const isProd: boolean = process.env.NODE_ENV === 'production'
+export const isServer: boolean = process.server
+export const isClient: boolean = process.client
diff --git a/test/unit/.eslintrc.js b/test/unit/.eslintrc.js
index 57c65b31b..5a68b15df 100644
--- a/test/unit/.eslintrc.js
+++ b/test/unit/.eslintrc.js
@@ -4,5 +4,13 @@ module.exports = {
rules: {
'import/no-named-as-default-member': ['off'],
'@intlify/vue-i18n/no-raw-text': ['off'],
+ 'no-restricted-imports': [
+ 'error',
+ {
+ name: 'pinia',
+ message:
+ 'Please import pinia test utils from `~~/test/unit/test-utils/pinia`. The test-utils version ensures proper setup of universally necessary Nuxt context mocks.',
+ },
+ ],
},
}
diff --git a/test/unit/specs/components/AudioTrack/v-audio-track.spec.js b/test/unit/specs/components/AudioTrack/v-audio-track.spec.js
index 850cdadfa..dea8b2f6e 100644
--- a/test/unit/specs/components/AudioTrack/v-audio-track.spec.js
+++ b/test/unit/specs/components/AudioTrack/v-audio-track.spec.js
@@ -1,6 +1,11 @@
import { render } from '@testing-library/vue'
import Vuei18n from 'vue-i18n'
-import { setActivePinia, createPinia, PiniaVuePlugin } from 'pinia'
+
+import {
+ setActivePinia,
+ createPinia,
+ PiniaVuePlugin,
+} from '~~/test/unit/test-utils/pinia'
import { getAudioObj } from '~~/test/unit/fixtures/audio'
diff --git a/test/unit/specs/components/image-grid.spec.js b/test/unit/specs/components/image-grid.spec.js
index 2d89e20d5..d539a0c50 100644
--- a/test/unit/specs/components/image-grid.spec.js
+++ b/test/unit/specs/components/image-grid.spec.js
@@ -1,8 +1,10 @@
import { render, screen } from '@testing-library/vue'
import VueI18n from 'vue-i18n'
-import { createPinia, PiniaVuePlugin } from 'pinia'
+
import { createLocalVue } from '@vue/test-utils'
+import { PiniaVuePlugin, createPinia } from '~~/test/unit/test-utils/pinia'
+
import messages from '~/locales/en.json'
import VImageGrid from '~/components/VImageGrid/VImageGrid.vue'
diff --git a/test/unit/specs/components/related-images.spec.js b/test/unit/specs/components/related-images.spec.js
index 9add8e0d3..edb72161a 100644
--- a/test/unit/specs/components/related-images.spec.js
+++ b/test/unit/specs/components/related-images.spec.js
@@ -1,7 +1,8 @@
import VueI18n from 'vue-i18n'
import { createLocalVue } from '@vue/test-utils'
import { render, screen } from '@testing-library/vue'
-import { createPinia, PiniaVuePlugin } from 'pinia'
+
+import { PiniaVuePlugin, createPinia } from '~~/test/unit/test-utils/pinia'
import messages from '~/locales/en.json'
diff --git a/test/unit/specs/components/v-filter-checklist.spec.js b/test/unit/specs/components/v-filter-checklist.spec.js
index 6f1af83a3..34fc12440 100644
--- a/test/unit/specs/components/v-filter-checklist.spec.js
+++ b/test/unit/specs/components/v-filter-checklist.spec.js
@@ -1,7 +1,7 @@
import { createLocalVue } from '@vue/test-utils'
import { fireEvent, render, screen } from '@testing-library/vue'
-import { PiniaVuePlugin, createPinia } from 'pinia'
+import { PiniaVuePlugin, createPinia } from '~~/test/unit/test-utils/pinia'
import { useI18n } from '~/composables/use-i18n'
diff --git a/test/unit/specs/components/v-search-grid-filter.spec.js b/test/unit/specs/components/v-search-grid-filter.spec.js
index 31c8309a9..564ef2cdc 100644
--- a/test/unit/specs/components/v-search-grid-filter.spec.js
+++ b/test/unit/specs/components/v-search-grid-filter.spec.js
@@ -1,7 +1,8 @@
import { fireEvent, render, screen } from '@testing-library/vue'
import { createLocalVue } from '@vue/test-utils'
import VueI18n from 'vue-i18n'
-import { createPinia, PiniaVuePlugin } from 'pinia'
+
+import { PiniaVuePlugin, createPinia } from '~~/test/unit/test-utils/pinia'
import { useSearchStore } from '~/stores/search'
diff --git a/test/unit/specs/components/v-sources-table.spec.js b/test/unit/specs/components/v-sources-table.spec.js
index 7fbba4cfb..8a082dcc7 100644
--- a/test/unit/specs/components/v-sources-table.spec.js
+++ b/test/unit/specs/components/v-sources-table.spec.js
@@ -1,9 +1,11 @@
import { render, screen } from '@testing-library/vue'
import userEvent from '@testing-library/user-event'
-import { PiniaVuePlugin } from 'pinia'
+
import { createTestingPinia } from '@pinia/testing'
import VueI18n from 'vue-i18n'
+import { PiniaVuePlugin } from '~~/test/unit/test-utils/pinia'
+
import VSourcesTableVue from '~/components/VSourcesTable.vue'
const enMessages = require('~/locales/en.json')
diff --git a/test/unit/specs/pages/browse-page.spec.js b/test/unit/specs/pages/browse-page.spec.js
index 05f8f3a19..5e323130e 100644
--- a/test/unit/specs/pages/browse-page.spec.js
+++ b/test/unit/specs/pages/browse-page.spec.js
@@ -1,7 +1,8 @@
import { render, screen } from '@testing-library/vue'
import { createLocalVue } from '@vue/test-utils'
import { ref } from '@nuxtjs/composition-api'
-import { createPinia, PiniaVuePlugin } from 'pinia'
+
+import { createPinia, PiniaVuePlugin } from '~~/test/unit/test-utils/pinia'
import SearchIndex from '~/pages/search.vue'
import { IMAGE } from '~/constants/media'
diff --git a/test/unit/specs/plugins/api-token.server.spec.ts b/test/unit/specs/plugins/api-token.server.spec.ts
new file mode 100644
index 000000000..9a253a4af
--- /dev/null
+++ b/test/unit/specs/plugins/api-token.server.spec.ts
@@ -0,0 +1,306 @@
+import { mockCreateApiService } from '~~/test/unit/test-utils/api-service-mock'
+
+import apiTokenPlugin, {
+ Process,
+ expiryThreshold,
+} from '~/plugins/api-token.server'
+
+import type { AxiosRequestConfig } from 'axios'
+
+import type { Context } from '@nuxt/types'
+
+// Comment this out if you need to debug the tests as the logs are quite helpful
+jest.mock('~/utils/console', () => ({
+ log: () => {
+ /* noop */
+ },
+ error: () => {
+ /* noop */
+ },
+}))
+
+export declare let process: NodeJS.Process & Process
+
+const matchTokenDataRequest = /auth_tokens\/token/
+
+type $config = Partial<{
+ apiClientId: string
+ apiClientSecret: string
+}>
+
+const defaultConfig: Required<$config> = {
+ apiClientId: 'abcdefg_client_i_d',
+ apiClientSecret: 'shhhhhhhhh_1234_super_secret',
+}
+
+const matchTokenDataRequestBody = new URLSearchParams({
+ client_id: defaultConfig.apiClientId,
+ client_secret: defaultConfig.apiClientSecret,
+ grant_type: 'client_credentials',
+}).toString()
+
+const getMockContext = ($config: $config = defaultConfig) =>
+ ({
+ $sentry: {
+ captureException: jest.fn(),
+ },
+ $config: $config,
+ } as unknown as Context)
+
+const mockInject = jest.fn()
+
+const frozenNow = Date.now()
+const frozenSeconds = Math.floor(frozenNow / 1e3)
+jest.spyOn(global.Date, 'now').mockReturnValue(frozenNow)
+const twelveHoursInSeconds = 12 * 3600
+let tokenCount = 1
+const getMockTokenResponse = (expires_in = twelveHoursInSeconds) => ({
+ access_token: `abcd1234_${tokenCount++}`,
+ expires_in,
+})
+
+const mockResponseAndAssertData =
+ (response: [number, unknown?], data = matchTokenDataRequestBody) =>
+ (config: AxiosRequestConfig) => {
+ expect(config.data).toEqual(data)
+ return response
+ }
+
+const defaultPromise = Promise.resolve()
+
+describe('api-token.server plugin', () => {
+ afterEach(() => {
+ mockInject.mockReset()
+ process.tokenData = {
+ accessToken: '',
+ accessTokenExpiry: 0,
+ }
+ process.tokenFetching = defaultPromise
+ })
+
+ describe('successful token retrieval', () => {
+ it('should save the token into the process and inject into the context', async () => {
+ const mockTokenResponse = getMockTokenResponse()
+ mockCreateApiService((axiosMockAdapter) => {
+ axiosMockAdapter
+ .onPost(matchTokenDataRequest)
+ .replyOnce(mockResponseAndAssertData([200, mockTokenResponse]))
+ })
+
+ await apiTokenPlugin(getMockContext(), mockInject)
+
+ expect(process.tokenData).toMatchObject({
+ accessToken: mockTokenResponse.access_token,
+ accessTokenExpiry: frozenSeconds + twelveHoursInSeconds,
+ })
+
+ expect(mockInject).toHaveBeenCalledWith(
+ 'openverseApiToken',
+ process.tokenData.accessToken
+ )
+ })
+
+ it('should re-retrieve the token when about to expire', async () => {
+ const mockTokenResponse = getMockTokenResponse(expiryThreshold - 1)
+ const nextMockTokenResponse = getMockTokenResponse()
+ mockCreateApiService((axiosMockAdapter) => {
+ axiosMockAdapter
+ .onPost(matchTokenDataRequest)
+ .replyOnce(mockResponseAndAssertData([200, mockTokenResponse]))
+
+ .onPost(matchTokenDataRequest)
+ .replyOnce(mockResponseAndAssertData([200, nextMockTokenResponse]))
+ })
+
+ await apiTokenPlugin(getMockContext(), mockInject)
+ await apiTokenPlugin(getMockContext(), mockInject)
+
+ expect(process.tokenData).toMatchObject({
+ accessToken: nextMockTokenResponse.access_token,
+ accessTokenExpiry: frozenSeconds + twelveHoursInSeconds,
+ })
+ })
+
+ it('should not request a new token if the token is not about to expire', async () => {
+ const mockTokenResponse = getMockTokenResponse(twelveHoursInSeconds)
+ const nextMockTokenResponse = getMockTokenResponse()
+ mockCreateApiService((axiosMockAdapter) => {
+ axiosMockAdapter
+ .onPost(matchTokenDataRequest)
+ .replyOnce(mockResponseAndAssertData([200, mockTokenResponse]))
+
+ .onPost(matchTokenDataRequest)
+ .replyOnce(mockResponseAndAssertData([200, nextMockTokenResponse]))
+ })
+
+ await apiTokenPlugin(getMockContext(), mockInject)
+ await apiTokenPlugin(getMockContext(), mockInject)
+
+ expect(process.tokenData).toMatchObject({
+ accessToken: mockTokenResponse.access_token,
+ accessTokenExpiry: frozenSeconds + twelveHoursInSeconds,
+ })
+ })
+
+ it('subsequent requests should all block on the same token retrieval promise', async () => {
+ /**
+ * This test is pretty complicated because we need to simulate
+ * multiple requests coming in at the same time with requests
+ * to the token API resolving only after the multiple
+ * requests have come in. If we didn't cause the request for the
+ * token to block until we'd fired off all three requests then
+ * the first request could resolve before the other two had a chance
+ * to check the mutex and await on the fetching promise.
+ *
+ * This relies on the behavior of the Node event loop where
+ * several async functions called synchronously in succession will exectue
+ * up until the first blocking `await` and then return the promise. This allows
+ * us to effectively get all three of the async api token plugin function
+ * calls up to the first blocking await which will either be the the call to
+ * `refreshApiAccessToken` which makes the axios call (blocked by the adapter
+ * mock in this test) _or_ awaiting the promise shared by the entire process.
+ */
+ const mockTokenResponse = getMockTokenResponse()
+ const nextMockTokenResponse = getMockTokenResponse()
+ let resolveFirstRequestPromise: undefined | ((value: unknown) => void) =
+ undefined
+ const resolveFirstRequest = async () => {
+ while (!resolveFirstRequestPromise) {
+ await new Promise((r) => setTimeout(r, 1))
+ }
+ resolveFirstRequestPromise({})
+ }
+
+ mockCreateApiService((mockAdapter) => {
+ mockAdapter
+ .onPost(matchTokenDataRequest)
+ .replyOnce(async () => {
+ const promise = new Promise((resolve) => {
+ resolveFirstRequestPromise = resolve as () => void
+ })
+
+ await promise
+
+ return [200, mockTokenResponse]
+ })
+
+ .onPost(matchTokenDataRequest)
+ .replyOnce(mockResponseAndAssertData([200, nextMockTokenResponse]))
+ })
+
+ const promises = [
+ apiTokenPlugin(getMockContext(), mockInject),
+ apiTokenPlugin(getMockContext(), mockInject),
+ apiTokenPlugin(getMockContext(), mockInject),
+ ]
+
+ await resolveFirstRequest()
+ await Promise.all(promises)
+
+ // If the process tokenData still matches the first
+ // request's return then we know that all three requests
+ // used the same response.
+ expect(process.tokenData).toMatchObject({
+ accessToken: mockTokenResponse.access_token,
+ accessTokenExpiry: frozenSeconds + twelveHoursInSeconds,
+ })
+ })
+ })
+
+ describe('unnecessful token retrieval', () => {
+ it('should record the error in sentry', async () => {
+ mockCreateApiService((mockAdapter) => {
+ mockAdapter
+ .onPost(matchTokenDataRequest)
+ .replyOnce(mockResponseAndAssertData([418]))
+ })
+
+ const mockContext = getMockContext()
+ let capturedError: Error | undefined = undefined
+ ;(
+ mockContext.$sentry.captureException as jest.Mock
+ ).mockImplementationOnce((e: Error) => {
+ capturedError = e
+ })
+
+ await apiTokenPlugin(mockContext, mockInject)
+
+ expect(mockContext.$sentry.captureException).toHaveBeenCalledTimes(1)
+ expect(capturedError).not.toBeUndefined()
+ expect((capturedError as unknown as Error).message).toMatch(
+ 'Unable to retrieve API token. Request failed with status code 418'
+ )
+ })
+
+ it('should empty the token data', async () => {
+ mockCreateApiService((mockAdapter) => {
+ mockAdapter
+ .onPost(matchTokenDataRequest)
+ .replyOnce(
+ mockResponseAndAssertData([
+ 200,
+ getMockTokenResponse(expiryThreshold - 1),
+ ])
+ )
+
+ .onPost(matchTokenDataRequest)
+ .replyOnce(mockResponseAndAssertData([418]))
+ })
+
+ await apiTokenPlugin(getMockContext(), mockInject)
+ expect(process.tokenData.accessToken).not.toEqual('')
+ await apiTokenPlugin(getMockContext(), mockInject)
+ expect(process.tokenData.accessToken).toEqual('')
+ })
+
+ it('should properly release the mutex and allow for subsequent requests to retry the token refresh', async () => {
+ const finalTokenResponse = getMockTokenResponse()
+ mockCreateApiService((mockAdapter) => {
+ mockAdapter
+ .onPost(matchTokenDataRequest)
+ .replyOnce(
+ mockResponseAndAssertData([
+ 200,
+ getMockTokenResponse(expiryThreshold - 1),
+ ])
+ )
+
+ .onPost(matchTokenDataRequest)
+ .replyOnce(mockResponseAndAssertData([418]))
+
+ .onPost(matchTokenDataRequest)
+ .replyOnce(mockResponseAndAssertData([200, finalTokenResponse]))
+ })
+
+ await apiTokenPlugin(getMockContext(), mockInject)
+ await apiTokenPlugin(getMockContext(), mockInject)
+ expect(process.fetchingMutex.isLocked()).toBe(false)
+ await apiTokenPlugin(getMockContext(), mockInject)
+ expect(process.tokenData.accessToken).toEqual(
+ finalTokenResponse.access_token
+ )
+ })
+ })
+
+ describe('missing client credentials', () => {
+ describe('completely missing', () => {
+ it('should not make any requests and fall back to tokenless', async () => {
+ await apiTokenPlugin(getMockContext({}), mockInject)
+ expect(mockInject).toHaveBeenCalledWith('openverseApiToken', '')
+ })
+ })
+
+ describe('explicitly undefined', () => {
+ it('should not make any requests and fall back to tokenless', async () => {
+ await apiTokenPlugin(
+ getMockContext({
+ apiClientId: undefined,
+ apiClientSecret: undefined,
+ }),
+ mockInject
+ )
+ expect(mockInject).toHaveBeenCalledWith('openverseApiToken', '')
+ })
+ })
+ })
+})
diff --git a/test/unit/specs/stores/active-media-store.spec.js b/test/unit/specs/stores/active-media-store.spec.js
index 81446e29d..03a3a3ee0 100644
--- a/test/unit/specs/stores/active-media-store.spec.js
+++ b/test/unit/specs/stores/active-media-store.spec.js
@@ -1,4 +1,4 @@
-import { setActivePinia, createPinia } from 'pinia'
+import { setActivePinia, createPinia } from '~~/test/unit/test-utils/pinia'
import { AUDIO } from '~/constants/media'
diff --git a/test/unit/specs/stores/feature-flag-store.spec.js b/test/unit/specs/stores/feature-flag-store.spec.js
index e554883d9..83bc7b95b 100644
--- a/test/unit/specs/stores/feature-flag-store.spec.js
+++ b/test/unit/specs/stores/feature-flag-store.spec.js
@@ -1,4 +1,4 @@
-import { setActivePinia, createPinia } from 'pinia'
+import { setActivePinia, createPinia } from '~~/test/unit/test-utils/pinia'
import { useFeatureFlagStore, getFlagStatus } from '~/stores/feature-flag'
import { OFF, ON } from '~/constants/feature-flag'
diff --git a/test/unit/specs/stores/media-store.spec.js b/test/unit/specs/stores/media-store.spec.js
index 30c71717e..2ec202e0b 100644
--- a/test/unit/specs/stores/media-store.spec.js
+++ b/test/unit/specs/stores/media-store.spec.js
@@ -1,11 +1,10 @@
-import { createPinia, setActivePinia } from 'pinia'
+import { setActivePinia, createPinia } from '~~/test/unit/test-utils/pinia'
import { deepClone } from '~/utils/clone'
import { initialResults, useMediaStore } from '~/stores/media'
import { useSearchStore } from '~/stores/search'
import { ALL_MEDIA, AUDIO, IMAGE, supportedMediaTypes } from '~/constants/media'
-import { services } from '~/stores/media/services'
import { initialFetchState } from '~/composables/use-fetch-state'
jest.mock('axios', () => ({
@@ -48,25 +47,26 @@ const searchResults = (mediaType) => ({
page_count: 2,
})
+const mockImplementation = (mediaType) => () =>
+ Promise.resolve({ ...searchResults(mediaType) })
+const mockSearchAudio = jest.fn().mockImplementation(mockImplementation(AUDIO))
+const mockSearchImage = jest.fn().mockImplementation(mockImplementation(IMAGE))
+const mockGetMediaDetail = jest.fn()
jest.mock('~/stores/media/services', () => ({
- services: {
- audio: /** @type {typeof import('~/data/services').MediaService} */ ({
- search: jest.fn(),
- getMediaDetail: jest.fn(),
- }),
- image: /** @type {typeof import('~/data/services').MediaService} */ ({
- search: jest.fn(),
- getMediaDetail: jest.fn(),
- }),
+ initServices: {
+ audio: () =>
+ /** @type {typeof import('~/data/services').MediaService} */ ({
+ search: mockSearchAudio,
+ getMediaDetail: mockGetMediaDetail,
+ }),
+ image: () =>
+ /** @type {typeof import('~/data/services').MediaService} */ ({
+ search: mockSearchImage,
+ getMediaDetail: mockGetMediaDetail,
+ }),
},
}))
-for (const mediaType of [AUDIO, IMAGE]) {
- services[mediaType].search.mockImplementation(() =>
- Promise.resolve({ ...searchResults(mediaType) })
- )
-}
-
describe('Media Store', () => {
describe('state', () => {
it('sets default state', () => {
@@ -191,10 +191,9 @@ describe('Media Store', () => {
setActivePinia(createPinia())
})
afterEach(() => {
- services.audio.search.mockClear()
- services.image.search.mockClear()
- services.audio.getMediaDetail.mockClear()
- services.image.getMediaDetail.mockClear()
+ mockSearchAudio.mockClear()
+ mockSearchImage.mockClear()
+ mockGetMediaDetail.mockClear()
})
it('setMedia updates state persisting images', () => {
@@ -297,7 +296,7 @@ describe('Media Store', () => {
it('fetchSingleMediaType throws an error if result count is 0', async () => {
const mediaType = IMAGE
- services[mediaType].search.mockImplementationOnce(() =>
+ mockSearchImage.mockImplementationOnce(() =>
Promise.resolve({
results: {},
result_count: 0,
diff --git a/test/unit/specs/stores/nav-store.spec.js b/test/unit/specs/stores/nav-store.spec.js
index ff798abbf..3986e0231 100644
--- a/test/unit/specs/stores/nav-store.spec.js
+++ b/test/unit/specs/stores/nav-store.spec.js
@@ -1,4 +1,4 @@
-import { setActivePinia, createPinia } from 'pinia'
+import { setActivePinia, createPinia } from '~~/test/unit/test-utils/pinia'
import { useNavigationStore } from '~/stores/navigation'
diff --git a/test/unit/specs/stores/provider.spec.js b/test/unit/specs/stores/provider.spec.js
index 496360964..663757bf0 100644
--- a/test/unit/specs/stores/provider.spec.js
+++ b/test/unit/specs/stores/provider.spec.js
@@ -1,10 +1,10 @@
-import { createPinia, setActivePinia } from 'pinia'
+import { setActivePinia, createPinia } from '~~/test/unit/test-utils/pinia'
import { warn } from '~/utils/console'
import { AUDIO, IMAGE, supportedMediaTypes } from '~/constants/media'
import { useSearchStore } from '~/stores/search'
import { useProviderStore } from '~/stores/provider'
-import { providerServices } from '~/data/media-provider-service'
+import { initProviderServices } from '~/data/media-provider-service'
import { initialFetchState } from '~/composables/use-fetch-state'
jest.mock('axios', () => ({
@@ -43,23 +43,20 @@ const mockData = [
},
]
+const mockImplementation = () => Promise.resolve({ data: [...mockData] })
+const mock = jest.fn().mockImplementation(mockImplementation)
jest.mock('~/data/media-provider-service', () => ({
- providerServices: {
- audio:
+ initProviderServices: {
+ audio: () =>
/** @type {typeof import('~/data/media-provider-services').MediaProviderService} */ ({
- getProviderStats: jest.fn(),
+ getProviderStats: mock,
}),
- image:
+ image: () =>
/** @type {typeof import('~/data/media-provider-services').MediaProviderService} */ ({
- getProviderStats: jest.fn(),
+ getProviderStats: mock,
}),
},
}))
-for (const mediaType of supportedMediaTypes) {
- providerServices[mediaType].getProviderStats.mockImplementation(() =>
- Promise.resolve({ data: [...mockData] })
- )
-}
describe('Provider Store', () => {
let providerStore
@@ -68,8 +65,7 @@ describe('Provider Store', () => {
providerStore = useProviderStore()
})
afterEach(() => {
- providerServices.audio.getProviderStats.mockClear()
- providerServices.image.getProviderStats.mockClear()
+ mock.mockClear()
})
afterAll(() => {
warn.mockReset()
@@ -112,9 +108,11 @@ describe('Provider Store', () => {
it('fetchMediaProviders on error', async () => {
for (const mediaType of supportedMediaTypes) {
- providerServices[mediaType].getProviderStats.mockImplementation(() =>
- Promise.reject(new Error('Not found'))
- )
+ initProviderServices[mediaType] = () => ({
+ getProviderStats: jest
+ .fn()
+ .mockImplementation(() => Promise.reject(new Error('Not found'))),
+ })
}
const searchStore = useSearchStore()
await providerStore.fetchMediaProviders()
diff --git a/test/unit/specs/stores/search-store.spec.js b/test/unit/specs/stores/search-store.spec.js
index 0e9d26b38..1c22f1ef5 100644
--- a/test/unit/specs/stores/search-store.spec.js
+++ b/test/unit/specs/stores/search-store.spec.js
@@ -1,7 +1,7 @@
-import { setActivePinia, createPinia } from 'pinia'
-
import { nextTick } from '@nuxtjs/composition-api'
+import { setActivePinia, createPinia } from '~~/test/unit/test-utils/pinia'
+
import { filterData, mediaFilterKeys } from '~/constants/filters'
import {
ALL_MEDIA,
diff --git a/test/unit/specs/stores/single-result-store.spec.js b/test/unit/specs/stores/single-result-store.spec.js
index 1f66a084f..2047e19b8 100644
--- a/test/unit/specs/stores/single-result-store.spec.js
+++ b/test/unit/specs/stores/single-result-store.spec.js
@@ -1,10 +1,9 @@
-import { createPinia, setActivePinia } from 'pinia'
+import { createPinia, setActivePinia } from '~~/test/unit/test-utils/pinia'
import { initialFetchState } from '~/composables/use-fetch-state'
import { AUDIO, IMAGE, supportedMediaTypes } from '~/constants/media'
import { useMediaStore } from '~/stores/media'
import { useSingleResultStore } from '~/stores/media/single-result'
-import { services } from '~/stores/media/services'
const detailData = {
[AUDIO]: { title: 'audioDetails', id: 'audio1', frontendMediaType: AUDIO },
@@ -14,21 +13,32 @@ jest.mock('axios', () => ({
...jest.requireActual('axios'),
isAxiosError: jest.fn((obj) => 'response' in obj),
}))
+
+const mockImplementation = (mediaType) => () =>
+ Promise.resolve(detailData[mediaType])
+const mockGetMediaDetailAudio = jest
+ .fn()
+ .mockImplementation(mockImplementation(AUDIO))
+const mockGetMediaDetailImage = jest
+ .fn()
+ .mockImplementation(mockImplementation(IMAGE))
+const mocks = {
+ audio: mockGetMediaDetailAudio,
+ image: mockGetMediaDetailImage,
+}
jest.mock('~/stores/media/services', () => ({
- services: {
- audio: /** @type {import('~/data/services').MediaService} */ ({
- getMediaDetail: jest.fn(),
- }),
- image: /** @type {import('~/data/services').MediaService} */ ({
- getMediaDetail: jest.fn(),
- }),
+ initServices: {
+ audio: () =>
+ /** @type {import('~/data/services').MediaService} */ ({
+ getMediaDetail: mockGetMediaDetailAudio,
+ }),
+ image: () =>
+ /** @type {import('~/data/services').MediaService} */ ({
+ getMediaDetail: mockGetMediaDetailImage,
+ }),
},
}))
-for (const mediaType of [AUDIO, IMAGE]) {
- services[mediaType].getMediaDetail.mockImplementation(() =>
- Promise.resolve(detailData[mediaType])
- )
-}
+
describe('Media Item Store', () => {
describe('state', () => {
it('sets default state', () => {
@@ -45,6 +55,10 @@ describe('Media Item Store', () => {
setActivePinia(createPinia())
useMediaStore()
})
+ afterEach(() => {
+ mockGetMediaDetailAudio.mockClear()
+ mockGetMediaDetailImage.mockClear()
+ })
it.each(supportedMediaTypes)(
'fetchMediaItem (%s) fetches a new media if none is found in the store',
@@ -73,7 +87,7 @@ describe('Media Item Store', () => {
async (type) => {
const expectedErrorMessage = 'error'
- services[type].getMediaDetail.mockImplementationOnce(() =>
+ mocks[type].mockImplementationOnce(() =>
Promise.reject(new Error(expectedErrorMessage))
)
@@ -88,7 +102,7 @@ describe('Media Item Store', () => {
it.each(supportedMediaTypes)(
'fetchMediaItem on 404 sets fetchingError and throws a new error',
async (type) => {
- services[type].getMediaDetail.mockImplementationOnce(() =>
+ mocks[type].mockImplementationOnce(() =>
Promise.reject({ response: { status: 404 } })
)
const singleResultStore = useSingleResultStore()
diff --git a/test/unit/test-utils/api-service-mock.ts b/test/unit/test-utils/api-service-mock.ts
new file mode 100644
index 000000000..98334caba
--- /dev/null
+++ b/test/unit/test-utils/api-service-mock.ts
@@ -0,0 +1,80 @@
+import MockAdapter from 'axios-mock-adapter'
+
+import * as apiService from '~/data/api-service'
+
+jest.mock('~/data/api-service', () => ({ createApiService: jest.fn() }))
+const originalApiService = jest.requireActual('~/data/api-service')
+
+const createApiService = apiService.createApiService as jest.Mock<
+ ReturnType<typeof apiService.createApiService>,
+ Parameters<typeof apiService.createApiService>
+>
+
+/**
+ * Creates an API Serivce that get's reused throughout the lifetime of
+ * the current context in which it is called.
+ *
+ * @example
+ * ```typescript
+ * it('should get some response', async () => {
+ * mockCreateApiService((mockAdapter) => {
+ * mockAdapter
+ * .onGet(/hello/).replyOnce(200, ', world!')
+ * .onGet(/hello/).replyOnce(200, ', Openverse!')
+ * })
+ *
+ * expect(
+ * await createApiService().get('hello')
+ * ).toEqual(', world!')
+ *
+ * expect(
+ * await createApiService().get('hello')
+ * ).toEqual(', Openverse!')
+ * })
+ * ```
+ *
+ * Note in the example that despite `createApiService` being called
+ * twice, the mock adapter is not re-applied and the second registered
+ * response still works as expected.
+ *
+ * With the particual way this mock creation function works,
+ * even if `createApiService` is called several times during
+ * the lifecycle of a particular test context, the same `apiService`
+ * instace will be reused for each call. This is done to preserve
+ * lists of responses applied to the mock adapter in the `applyMocks`
+ * callback. Otherwise, if `createApiService` is called more than
+ * once per test, then each time it is called will cause a new
+ * call to `applyMocks` and reset the stack of responses on the
+ * mock adapter (as it will be using a new axios client anyway).
+ *
+ * This may cause unforeseen difficulties with using this mock
+ * in other tests. For now this is the only sane way to isolate
+ * the `createApiService` behavior. Ideally the axios client would
+ * be put into Nuxt context so that it can be universally mocked
+ * throughout the lifecycle of plugin, component, and store operations.
+ *
+ * @see https://github.com/ctimmerm/axios-mock-adapter
+ *
+ * @param applyMocks - Callback function used to apply mock
+ * responses using the `axios-mock-adapter` library
+ */
+export const mockCreateApiService = (
+ applyMocks: (mockAdapter: MockAdapter) => void
+): void => {
+ let apiService: apiService.ApiService | undefined
+ afterEach(() => {
+ apiService = undefined
+ })
+ createApiService.mockImplementation((options) => {
+ // Only ever generate the mock once
+ if (apiService) return apiService
+
+ apiService = originalApiService.createApiService(
+ options
+ ) as apiService.ApiService
+
+ applyMocks(new MockAdapter(apiService.client))
+
+ return apiService
+ })
+}
diff --git a/test/unit/test-utils/pinia.js b/test/unit/test-utils/pinia.js
new file mode 100644
index 000000000..7a21c51d0
--- /dev/null
+++ b/test/unit/test-utils/pinia.js
@@ -0,0 +1,13 @@
+// eslint-disable-next-line no-restricted-imports
+import * as pinia from 'pinia'
+
+export const createPinia = () =>
+ pinia.createPinia().use(() => ({
+ $nuxt: {
+ $openverseApiToken: '',
+ },
+ }))
+
+export const setActivePinia = pinia.setActivePinia
+
+export const PiniaVuePlugin = pinia.PiniaVuePlugin