Skip to content

Commit

Permalink
fix: buffers
Browse files Browse the repository at this point in the history
  • Loading branch information
rafaelcr committed Feb 17, 2023
1 parent 790cbf7 commit ae45e06
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 6 deletions.
17 changes: 17 additions & 0 deletions src/api/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,20 @@ export function parseDbInscriptions(items: DbInscription[]): InscriptionType[] {
export function parseDbInscription(item: DbInscription): InscriptionType {
return parseDbInscriptions([item])[0];
}

/**
* Decodes a `0x` prefixed hex string to a buffer.
* @param hex - A hex string with a `0x` prefix.
*/
export function hexToBuffer(hex: string): Buffer {
if (hex.length === 0) {
return Buffer.alloc(0);
}
if (!hex.startsWith('0x')) {
throw new Error(`Hex string is missing the "0x" prefix: "${hex}"`);
}
if (hex.length % 2 !== 0) {
throw new Error(`Hex string is an odd number of digits: ${hex}`);
}
return Buffer.from(hex.substring(2), 'hex');
}
16 changes: 11 additions & 5 deletions src/api/routes/inscriptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@ import { Type } from '@sinclair/typebox';
import { Value } from '@sinclair/typebox/value';
import { FastifyPluginCallback } from 'fastify';
import { Server } from 'http';
import { DEFAULT_API_LIMIT, parseDbInscription, parseDbInscriptions } from '../helpers';
import {
DEFAULT_API_LIMIT,
hexToBuffer,
parseDbInscription,
parseDbInscriptions,
} from '../helpers';
import {
BitcoinAddressParam,
BlockHeightParam,
Expand Down Expand Up @@ -91,7 +96,7 @@ export const InscriptionsRoutes: FastifyPluginCallback<
inscription_id: InscriptionIdParam,
}),
response: {
200: Type.String({ contentEncoding: 'binary' }),
200: Type.Uint8Array(),
404: NotFoundResponse,
},
},
Expand All @@ -101,12 +106,13 @@ export const InscriptionsRoutes: FastifyPluginCallback<
inscription_id: request.params.inscription_id,
});
if (inscription) {
const bytes = hexToBuffer(inscription.content);
await reply
.headers({
'Content-Type': inscription.content_type,
'Content-Length': inscription.content_length,
'content-type': inscription.content_type,
'content-length': inscription.content_length,
})
.send(inscription.content);
.send(bytes);
} else {
await reply.code(404).send(Value.Create(NotFoundResponse));
}
Expand Down
2 changes: 1 addition & 1 deletion src/pg/pg-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export class PgStore extends BasePgStore {
inscription_id: string;
}): Promise<DbInscriptionContent | undefined> {
const result = await this.sql<DbInscriptionContent[]>`
SELECT content
SELECT content, content_type, content_length
FROM inscriptions
WHERE inscription_id = ${args.inscription_id}
ORDER BY block_height DESC
Expand Down

0 comments on commit ae45e06

Please sign in to comment.