Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(node-fs): add support for multiple dirs #203

Merged
merged 8 commits into from
Jan 12, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
76 changes: 46 additions & 30 deletions src/storage/node-fs.ts
Original file line number Diff line number Diff line change
@@ -1,54 +1,71 @@
import type { Stats } from "node:fs";
import { resolve, parse, join } from "pathe";
import { createError } from "h3";
import { cachedPromise, getEnv } from "../utils";
import type { IPXStorage } from "../types";

export type NodeFSSOptions = {
dir?: string;
dir?: string | string[];
maxAge?: number;
};

function resolveDirs(options: NodeFSSOptions) {
if (!options.dir || !Array.isArray(options.dir)) {
const dir = resolve(options.dir || getEnv("IPX_FS_DIR") || ".");
return [dir];
}

return options.dir.map((dir) => {
return resolve(dir);
});
}

export function ipxFSStorage(_options: NodeFSSOptions = {}): IPXStorage {
const rootDir = resolve(_options.dir || getEnv("IPX_FS_DIR") || ".");
const dirs = resolveDirs(_options);
const maxAge = _options.maxAge || getEnv("IPX_FS_MAX_AGE");

const _resolve = (id: string) => {
const resolved = join(rootDir, id);
if (!isValidPath(resolved) || !resolved.startsWith(rootDir)) {
const _getFS = cachedPromise(() => import("node:fs/promises"));

const getMeta = async (id: string) => {
Aareksio marked this conversation as resolved.
Show resolved Hide resolved
const errors = new Set<string>();

for (const dir of dirs) {
const filePath = join(dir, id);

if (!isValidPath(filePath) || !filePath.startsWith(dir)) {
errors.add("IPX_FORBIDDEN_PATH");
}

try {
const fs = await _getFS();
Aareksio marked this conversation as resolved.
Show resolved Hide resolved
const stats = await fs.stat(filePath);
return { stats, filePath };
} catch (error: any) {
errors.add(
error.code === "ENOENT" ? "IPX_FILE_NOT_FOUND" : "IPX_FORBIDDEN_FILE",
pi0 marked this conversation as resolved.
Show resolved Hide resolved
);
}
}

if (errors.has("IPX_FORBIDDEN_FILE")) {
throw createError({
statusCode: 403,
statusText: `IPX_FORBIDDEN_PATH`,
message: `Forbidden path: ${id}`,
});
}
return resolved;
};

const _getFS = cachedPromise(() => import("node:fs/promises"));
throw createError({
statusCode: 404,
statusText: `IPX_FILE_NOT_FOUND`,
message: `File not found: ${id}`,
});
};

return {
name: "ipx:node-fs",
async getMeta(id) {
const fsPath = _resolve(id);
const { stats } = await getMeta(id);

let stats: Stats;
try {
const fs = await _getFS();
stats = await fs.stat(fsPath);
} catch (error: any) {
throw error.code === "ENOENT"
? createError({
statusCode: 404,
statusText: `IPX_FILE_NOT_FOUND`,
message: `File not found: ${id}`,
})
: createError({
statusCode: 403,
statusText: `IPX_FORBIDDEN_FILE`,
message: `File access forbidden: (${error.code}) ${id}`,
});
}
if (!stats.isFile()) {
throw createError({
statusCode: 400,
Expand All @@ -63,10 +80,9 @@ export function ipxFSStorage(_options: NodeFSSOptions = {}): IPXStorage {
};
},
async getData(id) {
const fsPath = _resolve(id);
const { filePath } = await getMeta(id);
const fs = await _getFS();
const contents = await fs.readFile(fsPath);
return contents;
return fs.readFile(filePath);
},
};
}
Expand Down
Binary file added test/assets-2/bliss.jpg
pi0 marked this conversation as resolved.
Show resolved Hide resolved
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added test/assets-2/unjs.jpg
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
38 changes: 38 additions & 0 deletions test/multiple-fs.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { resolve } from "pathe";
import { describe, it, expect, beforeAll } from "vitest";
import { IPX, createIPX, ipxFSStorage } from "../src";

describe("ipx", () => {
let ipx: IPX;

beforeAll(() => {
ipx = createIPX({
storage: ipxFSStorage({
// eslint-disable-next-line unicorn/prefer-module
dir: [resolve(__dirname, "assets"), resolve(__dirname, "assets-2")],
}),
});
});

it("local file 1", async () => {
const source = await ipx("giphy.gif");
const { data, format } = await source.process();
expect(data).toBeInstanceOf(Buffer);
expect(format).toBe("gif");
});

it("local file 2", async () => {
const source = await ipx("unjs.jpg");
const { data, format } = await source.process();
expect(data).toBeInstanceOf(Buffer);
expect(format).toBe("jpeg");
});

it("local file priority", async () => {
const source = await ipx("bliss.jpg");
const { data, format, meta } = await source.process();
expect(data).toBeInstanceOf(Buffer);
expect(format).toBe("jpeg");
expect(meta?.height).toBe(2160);
});
});