Skip to content

Commit

Permalink
Merge pull request #14 from deco-sites/task/ProdutoSimilar
Browse files Browse the repository at this point in the history
feat: adicionado novo loader de redirect
  • Loading branch information
marcusvl authored Apr 29, 2024
2 parents a0511f9 + 6bc212b commit cb7e51b
Show file tree
Hide file tree
Showing 3 changed files with 168 additions and 3 deletions.
6 changes: 3 additions & 3 deletions deno.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@
"deco-sites/lojastopmoveis/": "./",
"$store/": "./",
"deco-sites/std/": "https://denopkg.com/deco-sites/[email protected]/",
"$live/": "https://denopkg.com/deco-cx/deco@1.61.5/",
"deco/": "https://denopkg.com/deco-cx/deco@1.61.5/",
"$live/": "https://denopkg.com/deco-cx/deco@1.62.1/",
"deco/": "https://denopkg.com/deco-cx/deco@1.62.1/",
"$fresh/": "https://deno.land/x/[email protected]/",
"preact": "https://esm.sh/[email protected]",
"preact/": "https://esm.sh/[email protected]/",
Expand All @@ -41,7 +41,7 @@
"std/": "https://deno.land/[email protected]/",
"partytown/": "https://denopkg.com/deco-cx/[email protected]/",
"daisyui": "npm:[email protected]",
"apps/": "https://denopkg.com/deco-cx/[email protected].14/"
"apps/": "https://denopkg.com/deco-cx/[email protected].16/"
},
"lint": {
"rules": {
Expand Down
161 changes: 161 additions & 0 deletions loaders/RedirectsFromCsvWithEncoding.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
import { join } from "std/path/mod.ts";
import { Route } from "apps/website/flags/audience.ts";

const REDIRECT_TYPE_ENUM = ["temporary", "permanent"];

/** @titleBy from */
export interface Redirect {
from: string;
to: string;
type?: "temporary" | "permanent";
}

export interface Redirects {
/**
* @title The file url or path
*/
from?: string;
forcePermanentRedirects?: boolean;
redirects: Redirect[];
}

const getRedirectFromFile = async (
from: string,
forcePermanentRedirects?: boolean,
) => {
let redirectsRaw: string | null = null;
try {
if (from.startsWith("http")) {
redirectsRaw = await fetch(from).then((resp) => resp.text());
} else {
redirectsRaw = await Deno.readTextFile(
join(Deno.cwd(), join(...from.split("/"))),
);
}
} catch (e) {
console.error(e);
}

if (!redirectsRaw) {
return [];
}

const redirectsFromFiles: Redirects["redirects"] = redirectsRaw
?.split(/\r\n|\r|\n/)
.slice(1)
.map((row) => {
// this regex is necessary to handle csv with comma as part of value
const parts = row.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/);

const typeRowIndex = parts.findIndex((part: string) =>
REDIRECT_TYPE_ENUM.includes(part)
);

const type =
(parts[typeRowIndex] as Redirect["type"]) ?? forcePermanentRedirects
? "permanent"
: "temporary";

if (typeRowIndex !== -1) {
parts.splice(typeRowIndex, 1);
}

const last = parts[parts.length - 1];
parts.splice(parts.length - 1, 1);

return [
removeTrailingSlash(parts.join(",").replaceAll('"', "")),
removeTrailingSlash(last.replaceAll('"', "")),
type,
];
})
.filter(([from, to]) => from && to && from !== to)
.map(([from, to, type]) => ({
from,
to,
type: type as Redirect["type"],
}));

const processedRedirects = redirectsFromFiles.map(({ from, to, type }) => {
const encodedFrom = from
.replace(/[^a-zA-Z0-9\/]/g, (char) => encodeURIComponent(char));
if (encodedFrom !== from) {
return [
{
pathTemplate: from,
isHref: true,
handler: {
value: {
__resolveType: "website/handlers/redirect.ts",
to,
type,
},
},
},
{
pathTemplate: encodedFrom,
isHref: true,
handler: {
value: {
__resolveType: "website/handlers/redirect.ts",
to,
type,
},
},
},
];
} else {
return {
pathTemplate: from,
isHref: true,
handler: {
value: {
__resolveType: "website/handlers/redirect.ts",
to,
type,
},
},
};
}
}).flat();

return processedRedirects;
};

export const removeTrailingSlash = (path: string) =>
path.endsWith("/") && path.length > 1 ? path.slice(0, path.length - 1) : path;

const routesMap = new Map<string, Promise<Route[]>>();

export default async function redirect({
redirects,
from = "",
forcePermanentRedirects,
}: Redirects): Promise<Route[]> {
const current = routesMap.get(from);

if (!current) {
routesMap.set(
from,
from
? getRedirectFromFile(from, forcePermanentRedirects)
: Promise.resolve([]),
);
}

const redirectsFromFiles: Route[] = await routesMap.get(from)!;

const routes: Route[] = (redirects || []).map(({ from, to, type }) => ({
pathTemplate: from,
isHref: true,
handler: {
value: {
__resolveType: "website/handlers/redirect.ts",
to,
type,
},
},
}));

return [...redirectsFromFiles, ...routes];
}
4 changes: 4 additions & 0 deletions manifest.gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import * as $$$$$$$$$$$0 from "./apps/decohub.ts";
import * as $$$$$$$$$$$1 from "./apps/site.ts";
import * as $$$0 from "./loaders/RedirectsFromCsvWithEncoding.ts";
import * as $$$$$$0 from "./sections/Category/CategoryBanner.tsx";
import * as $$$$$$1 from "./sections/Category/CategoryBreadcrumb.tsx";
import * as $$$$$$2 from "./sections/Category/CategoryList.tsx";
Expand Down Expand Up @@ -48,6 +49,9 @@ import * as $$$$$$40 from "./sections/Social/InstagramPosts.tsx";
import * as $$$$$$41 from "./sections/Social/WhatsApp.tsx";

const manifest = {
"loaders": {
"deco-sites/lojastopmoveis/loaders/RedirectsFromCsvWithEncoding.ts": $$$0,
},
"sections": {
"deco-sites/lojastopmoveis/sections/Category/CategoryBanner.tsx": $$$$$$0,
"deco-sites/lojastopmoveis/sections/Category/CategoryBreadcrumb.tsx":
Expand Down

0 comments on commit cb7e51b

Please sign in to comment.