Skip to content

Commit

Permalink
Add the service worker to cache requests.
Browse files Browse the repository at this point in the history
  • Loading branch information
HosokawaR committed Nov 11, 2022
1 parent 88b8568 commit fb14363
Show file tree
Hide file tree
Showing 5 changed files with 98 additions and 4 deletions.
4 changes: 3 additions & 1 deletion .lintstagedrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ const tsconfigFilename = "tsconfig.staged.json";

const typecheckOnlyStaged = (stagedFilenames) => {
const tsconfig = JSON.parse(fs.readFileSync("tsconfig.json"));
tsconfig.include = stagedFilenames;
tsconfig.include = stagedFilenames.filter((filename) =>
filename.includes("/src/")
);
fs.writeFileSync(tsconfigFilename, JSON.stringify(tsconfig));
return `yarn typecheck --project ${tsconfigFilename}`;
};
Expand Down
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
"license": "MIT",
"scripts": {
"dev": "vite",
"typecheck": "vue-tsc --noEmit",
"build": "yarn typecheck && vite build",
"typecheck": "yarn build-serviceworker --noEmit && vue-tsc --noEmit",
"build": "yarn typecheck && vite build && yarn build-serviceworker",
"build:staging": "vite build --mode staging",
"preview": "yarn build && vite preview --port 8080",
"format": "prettier ./src --check",
Expand All @@ -15,6 +15,7 @@
"test": "jest",
"apigen": "rm -rf src/api && npx openapi2aspida",
"prepare": "husky install && rimraf ./node_modules/@types/react",
"build-serviceworker": "tsc -p serviceworkers/tsconfig.json",
"storybook": "start-storybook -p 6006",
"build-storybook": "yarn typecheck && build-storybook"
},
Expand Down
71 changes: 71 additions & 0 deletions serviceworkers/fallback.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import * as dotenv from "dotenv";

dotenv.config();

const CACHE_NAME = "TwinteFallback";
const VERSIONS = ["v1"];

let base_url: string;

if (process.env.NODE_ENV === "development") {
base_url = process.env.BASE_URL || "http://localhost:4000";
} else {
base_url = process.env.BASE_URL;
}

declare const self: ServiceWorkerGlobalScope;

self.addEventListener("install", () => {
VERSIONS.slice(0, Math.min(0, VERSIONS.length - 2)).forEach(
async (version) => {
await caches.delete(getCacheName(CACHE_NAME, version));
}
);
});

self.addEventListener("fetch", (event) => {
const request = event.request;

if (request.method !== "GET") return;
if (
!(
request.url.startsWith(base_url) ||
request.url.startsWith("https://fonts.googleapis.com/") ||
request.url.startsWith("https://fonts.gstatic.com/")
)
)
return;

event.respondWith(getResponseWithCaching(request));
});

const getCacheName = (name: string, version: string) => `${name}_${version}`;

const getResponseWithCaching = async (request: Request): Promise<Response> => {
const cache = await caches.open(
getCacheName(CACHE_NAME, VERSIONS[VERSIONS.length - 1])
);

let response: Response | undefined;

const hasCredentials = request.url.startsWith(base_url);

try {
response = await fetch(
request,
hasCredentials
? {
credentials: "include",
}
: {}
);
} catch (error) {
console.error(error);
response = await cache.match(request.url);
if (!response) throw new Error("There is no cache");
}

if (response.ok) cache.put(request, response.clone());

return response;
};
18 changes: 18 additions & 0 deletions serviceworkers/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"include": ["./**/*.ts"],
"compilerOptions": {
"sourceMap": true,
"module": "esnext",
"moduleResolution": "node",
"preserveValueImports": false,
"esModuleInterop": true,
"importsNotUsedAsValues": "remove",
"baseUrl": ".",
"paths": {
"~/*": ["./*"]
},
"lib": ["ES2021", "WebWorker"],
"types": ["node"],
"outDir": "../dist"
}
}
4 changes: 3 additions & 1 deletion src/ui/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
</template>

<script setup lang="ts">
import { onErrorCaptured, onMounted, ref } from "vue";
import { onErrorCaptured, ref } from "vue";
import { useRouter } from "vue-router";
import {
InternalServerError,
Expand All @@ -32,6 +32,8 @@ setSetting();
const router = useRouter();
navigator.serviceWorker.register("/fallback.js");
/** error */
const errorMessage = ref("");
Expand Down

0 comments on commit fb14363

Please sign in to comment.