UNPKG

@graphql-mesh/serve-runtime

Version:
27 lines (26 loc) 1.16 kB
import { fs, path } from '@graphql-mesh/cross-helpers'; import { pathExists } from '@graphql-mesh/utils'; export const useStaticFiles = ({ baseDir, staticFiles = 'public' }) => { return { onRequest({ request, url, endResponse, fetchAPI }) { if (request.method === 'GET') { let relativePath = url.pathname; if (relativePath === '/' || !relativePath) { relativePath = 'index.html'; } const absoluteStaticFilesPath = path.join(baseDir, staticFiles); const absolutePath = path.join(absoluteStaticFilesPath, relativePath); if (absolutePath.startsWith(absoluteStaticFilesPath)) { return pathExists(absolutePath).then(exists => { if (exists) { const readStream = fs.createReadStream(absolutePath); endResponse(new fetchAPI.Response(readStream, { status: 200, })); } }); } } }, }; };