Skip to content

Instantly share code, notes, and snippets.

@b-bot
Created May 29, 2024 07:55
Show Gist options
  • Save b-bot/db2b7d5081ff7c9f67938bc2742d6e26 to your computer and use it in GitHub Desktop.
Save b-bot/db2b7d5081ff7c9f67938bc2742d6e26 to your computer and use it in GitHub Desktop.
S3 Backend Upload
import { PutObjectCommand, S3Client } from '@aws-sdk/client-s3';
import {
MetadataAttributeType,
ProfileMetadataSchema,
profile,
} from '@lens-protocol/metadata';
import { v4 as uuidv4 } from 'uuid';
import { z } from 'zod';
import { env } from '~/env';
import { isDev } from '~/utils';
import { createTRPCRouter, protectedProcedure, publicProcedure } from '../trpc';
const client = new S3Client({});
// Cannot do authenticated requests as backend does not persist session
export const lensRouter = createTRPCRouter({
createMetadata: protectedProcedure
.input(
z.object({
name: z.union([
z.literal('website'),
z.literal('displayName'),
z.literal('bio'),
]),
value: z.string(),
}),
)
.mutation(async ({ input, ctx }) => {
const existingProfile = await lensClient.profile.fetch({
forProfileId: ctx.session.user.id,
});
try {
const { name, value } = input;
const profileAttributes = existingProfile?.metadata?.attributes?.map(
(a) => {
return {
type:
a.type.charAt(0).toUpperCase() + a.type.slice(1).toLowerCase(),
key: a.key,
value: a.value,
};
},
);
function getAttribute(key: string) {
if (name === key) {
return {
type: MetadataAttributeType.STRING,
key: name,
value,
};
}
for (const attribute of profileAttributes ?? []) {
if (attribute.key === key) {
return attribute;
}
}
}
const newAttributes = getAttribute(name);
const id = uuidv4();
const json = profile({
id,
name:
input.name === 'displayName'
? input.value
: existingProfile?.metadata?.displayName ?? undefined,
bio:
input.name === 'bio'
? input.value
: existingProfile?.metadata?.bio ?? undefined,
// @ts-expect-error - Lens types fucked
attributes: [
...(profileAttributes ?? []),
...(name && newAttributes ? [newAttributes] : []),
],
});
const Key = `${isDev() ? 'dev' : 'prod'}/${ctx.session.user.id}/${id}.json`;
const command = new PutObjectCommand({
Bucket: env.AWS_S3_BUCKET,
Key,
Body: Buffer.from(JSON.stringify(json), 'utf-8'),
ContentType: 'application/json',
});
if (ProfileMetadataSchema.parse(json)) {
await client.send(command);
return Key;
}
} catch (error) {
return false;
}
}),
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment