Dynamically create avatar based style argument #409
-
Hello! I know that to generate avatar we need to explicitly provide the style like import { createAvatar, Options } from '@dicebear/core';
import { JSONSchema7 } from 'json-schema';
import * as styles from '@dicebear/collection';
class InvalidArgumentError extends Error {
constructor(message: string) {
super(message);
this.name = 'InvalidArgumentError';
}
}
const styleMap = new Map(Object.entries(styles));
/**
* Generate the avatar and return its string representation.
* @param avatarStyle The avatar style to be used in the generation.
* @param options Options to generate the avatar.
* @returns String representation of the generated avatar.
*/
export function generateAvatar(avatarStyle: string, options: Options) {
const style: any = styleMap.get(avatarStyle);
if (!style) {
throw new InvalidArgumentError(`Style "${avatarStyle}" not found.`);
}
// style here is dynamic, fetched from the imported styles
return createAvatar(style, options).toString();
} Thank you! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Hi @pandabytes Your example is the best way to achieve the functionality. 👍 The ability to specify an avatar style via a string would mean that all avatar styles would have to be shipped with the library. Typically, not all avatar styles are used, so in a browser environment you would have to transfer an unnecessarily large amount of data. This is the reason why we separate library and avatar styles - it allows tree shaking. |
Beta Was this translation helpful? Give feedback.
Hi @pandabytes
Your example is the best way to achieve the functionality. 👍
The ability to specify an avatar style via a string would mean that all avatar styles would have to be shipped with the library. Typically, not all avatar styles are used, so in a browser environment you would have to transfer an unnecessarily large amount of data. This is the reason why we separate library and avatar styles - it allows tree shaking.