Skip to content

Commit

Permalink
fix schema validation on update tokens from figma
Browse files Browse the repository at this point in the history
  • Loading branch information
tomasfrancisco committed Aug 22, 2024
1 parent 92e86b9 commit 526f78a
Show file tree
Hide file tree
Showing 9 changed files with 43 additions and 65 deletions.
54 changes: 14 additions & 40 deletions packages/api/src/router/resources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@ import { z } from 'zod';
import { eq } from '@ds-project/database';

import { createTRPCRouter, protectedProcedure } from '../trpc';
import { InsertResourcesSchema, Resources } from '@ds-project/database/schema';
import {
InsertResourcesSchema,
PreprocessedTokensSchema,
Resources,
} from '@ds-project/database/schema';

export const resourcesRouter = createTRPCRouter({
byId: protectedProcedure
Expand Down Expand Up @@ -43,51 +47,21 @@ export const resourcesRouter = createTRPCRouter({
}),

updateDesignTokens: protectedProcedure
.input(InsertResourcesSchema.pick({ designTokens: true, name: true }))
.input(z.object({ name: z.string(), designTokens: z.any() }))
.mutation(async ({ ctx, input }) => {
console.log('🤯 Here');

const result = await ctx.database
.update(Resources)
.set(input)
.set({
...input,
// For some reason, if the validation happens at the input level, it gets a max stack call error.
// But moving it here it works 🤷🏻‍♂️
designTokens: PreprocessedTokensSchema.parse(input.designTokens),
})
.where(eq(Resources.name, input.name));
// TODO: Run update to Integration here ---> GitHub

/**
* // Update Github - TODO: turn into "update integrations" actions
const githubIntegration = await api.integrations.github();
if (!githubIntegration) {
throw new Error('No GitHub integration found');
}
const octokit = await getInstallationOctokit(
githubIntegration.data.installationId
);
const repositories = await octokit.request(
'GET /installation/repositories'
);
const repository = repositories.data.repositories.find(
(_repository) => _repository.id === githubIntegration.data.repositoryId
);
if (!repository) throw new Error('No repository found');
const base64Content = btoa(
JSON.stringify(validatedData.designTokens, null, 2)
);
await pushFile({
file: {
content: base64Content,
encoding: 'base64',
name: `/tokens.json`,
path: `${config.gitTokensPath}`,
},
installationId: githubIntegration.data.installationId,
owner: repository.owner.login,
repo: repository.name,
});
*/
return result;
}),

Expand Down
7 changes: 3 additions & 4 deletions packages/database/src/schema/resources/resources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,17 +30,16 @@ const DesignTokensSchema: z.ZodType<DesignTokens> = z.lazy(() =>
.catchall(
z.union([
DesignTokenSchema,
DesignTokensSchema,
z.lazy(() => DesignTokensSchema),
z.string(),
z.undefined(),
])
)
);

// PreprocessedTokens schema
const PreprocessedTokensSchema: z.ZodType<DesignToken | DesignTokens> = z.lazy(
() => z.union([DesignTokenSchema, PreprocessedTokensSchema])
);
export const PreprocessedTokensSchema: z.ZodType<DesignToken | DesignTokens> =
z.lazy(() => z.union([DesignTokenSchema, PreprocessedTokensSchema]));

/**
* Represents the resources linked to a design system.
Expand Down
7 changes: 4 additions & 3 deletions packages/figma-plugin/src/ui/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,16 @@ function App() {
api.resources.updateDesignTokens.useMutation();

useEffect(() => {
if (!fileName || state !== 'authorized') return;

AsyncMessage.ui
.request({
type: AsyncMessageTypes.GetDesignTokens,
})
.then(({ designTokens }) => {
console.log({ designTokens });
if (fileName) {
// void updateDesignTokens({ designTokens, name: fileName });
}

void updateDesignTokens({ designTokens, name: fileName });
})
.catch((error) => {
console.error('Error updating design tokens', error);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,10 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
setCredentials(_credentials);
setState('authorized');
setShouldUpdatePlugin(true);
} else {
setCredentials(undefined);
setState('unauthorized');
setShouldUpdatePlugin(true);
}
}, [credentials]);

Expand Down
2 changes: 2 additions & 0 deletions packages/figma-to-design-tokens/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,15 @@
"devDependencies": {
"@ds-project/prettier": "workspace:*",
"@ds-project/eslint": "workspace:*",
"@ds-project/typescript": "workspace:*",
"@figma/plugin-typings": "catalog:",
"style-dictionary": "^4.0.1",
"tsup": "^8.2.4",
"tsx": "^4.17.0",
"eslint": "catalog:"
},
"dependencies": {
"@ds-project/database": "workspace:*",
"color2k": "^2.0.3"
}
}
6 changes: 3 additions & 3 deletions packages/figma-to-design-tokens/src/converter.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { DesignToken, DesignTokens } from 'style-dictionary/types';
import { FigmaExtractedVariableCollection } from './types/figma';
import type { DesignToken, DesignTokens } from 'style-dictionary/types';
import type { FigmaExtractedVariableCollection } from './types/figma';
import { extractVariable } from './extractors/extract-variable';
import { notImplemented } from './filters/not-implemented';

export function convertFigmaVariablesToDesignTokens(
variableCollections: Array<FigmaExtractedVariableCollection>
variableCollections: FigmaExtractedVariableCollection[]
): DesignTokens {
return {
$type: 'figma-design-tokens',
Expand Down
7 changes: 6 additions & 1 deletion packages/figma-to-design-tokens/src/test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { convertFigmaVariablesToDesignTokens } from './converter';
import { InsertResourcesSchema } from '@ds-project/database/schema';

const designTokens = convertFigmaVariablesToDesignTokens([
{
Expand Down Expand Up @@ -213,5 +214,9 @@ const designTokens = convertFigmaVariablesToDesignTokens([
],
},
]);
const validDesignTokens = InsertResourcesSchema.pick({
designTokens: true,
name: true,
}).parse({ designTokens, name: 'Project DS' });

console.log('🧩 TOKENS', JSON.stringify(designTokens, null, 2));
console.log('🧩 TOKENS', JSON.stringify(validDesignTokens, null, 2));
15 changes: 1 addition & 14 deletions packages/figma-to-design-tokens/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,19 +1,6 @@
{
"extends": "@ds-project/typescript/internal-package.json",
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
"lib": ["DOM", "DOM.Iterable", "ESNext"],
"allowJs": false,
"skipLibCheck": true,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"typeRoots": ["./node_modules/@types", "./node_modules/@figma"]
},
"include": ["src"]
Expand Down
6 changes: 6 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 526f78a

Please sign in to comment.