0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2025-01-27 22:19:04 -05:00

Allow binary data to be returned from api routes in SSG (#6180)

* Allow binary data to be returned from api routes in SSG

* Adding a changeset
This commit is contained in:
Matthew Phillips 2023-02-08 16:42:52 -05:00 committed by GitHub
parent 919d0db428
commit 6fa6025b34
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 22 additions and 3 deletions

View file

@ -0,0 +1,5 @@
---
'astro': patch
---
Allow binary data to be returned from api routes in SSG

View file

@ -382,7 +382,7 @@ async function generatePath(
route: pageData.route, route: pageData.route,
}); });
let body: string; let body: string | Uint8Array;
let encoding: BufferEncoding | undefined; let encoding: BufferEncoding | undefined;
if (pageData.route.type === 'endpoint') { if (pageData.route.type === 'endpoint') {
const endpointHandler = mod as unknown as EndpointHandler; const endpointHandler = mod as unknown as EndpointHandler;
@ -392,7 +392,8 @@ async function generatePath(
throwIfRedirectNotAllowed(result.response, opts.settings.config); throwIfRedirectNotAllowed(result.response, opts.settings.config);
// If there's no body, do nothing // If there's no body, do nothing
if (!result.response.body) return; if (!result.response.body) return;
body = await result.response.text(); const ab = await result.response.arrayBuffer();
body = new Uint8Array(ab);
} else { } else {
body = result.body; body = result.body;
encoding = result.encoding; encoding = result.encoding;

View file

@ -41,4 +41,12 @@ describe('API routes', () => {
}); });
}); });
}); });
describe('Binary data', () => {
it('can be returned from a response', async () => {
const dat = await fixture.readFile('/binary.dat', null);
expect(dat.length).to.equal(1);
expect(dat[0]).to.equal(0xff);
});
});
}); });

View file

@ -0,0 +1,5 @@
import type { APIRoute } from 'astro';
export const get: APIRoute = async function () {
return new Response(new Uint8Array([0xff]));
};

View file

@ -167,7 +167,7 @@ export async function loadFixture(inlineConfig) {
}, },
pathExists: (p) => fs.existsSync(new URL(p.replace(/^\//, ''), config.outDir)), pathExists: (p) => fs.existsSync(new URL(p.replace(/^\//, ''), config.outDir)),
readFile: (filePath, encoding) => readFile: (filePath, encoding) =>
fs.promises.readFile(new URL(filePath.replace(/^\//, ''), config.outDir), encoding ?? 'utf8'), fs.promises.readFile(new URL(filePath.replace(/^\//, ''), config.outDir), encoding === undefined ? 'utf8' : encoding),
readdir: (fp) => fs.promises.readdir(new URL(fp.replace(/^\//, ''), config.outDir)), readdir: (fp) => fs.promises.readdir(new URL(fp.replace(/^\//, ''), config.outDir)),
glob: (p) => glob: (p) =>
fastGlob(p, { fastGlob(p, {