Skip to content

User ‐ Avatar

Rodrigo Tejero edited this page May 15, 2024 · 3 revisions

This is the current implementation for the avatar of the user entity. This function should go inside the user.controller.js.

This is how it works:

  1. If the user has an attachment, it will use the attachment as the avatar (the attachment is inside a meta called idAvatar).
  2. If no attachment present, it will generate a query to UI Avatars.
  3. If there is any kind of error, it will fallback to a "?" Avatar, also generated by UI Avatars.
static async avatar(req, res, next) {

	// Get query params for width and height
	const {
		size = 128,
		width = 128,
		height = 128,
		bold = true,
		background = '233D8F',
		color = 'FFFFFF',
		fontSize = 64,
		border = 2,
		chars = 2,
	} = req.query;

	// Set options
	const options = { size, width, height, bold, background, color, fontSize, border, chars };

	// covert options to query string
	const query = queryString.stringify(options);

	try {

		if(!req.params.id) throw new Error('No user id provided');

		console.log('Getting avatar for user:', req.params.id);

		const user = await UserService.findById(req.params.id);
		let attachment;

		// check if we got user.metas.idAvatar
		if(user.metas.idAvatar) {
			// get the attachment
			attachment = await AttachmentService.findById(user.metas.idAvatar);
		}

		// if we have an attachment, return the location of the attachment
		if(attachment && attachment.metas?.location) {

			res.redirect(attachment.metas.location);

		} else {

			// Get initials
			let initials = user.metas.firstname + ' ' + user.metas.lastname;

			// Trim initials
			initials = initials.trim();

			// if the initials is empty, use username
			if(!initials) initials = user.username;

			// if still empty, use NA
			if(!initials) initials = 'NA';

			res.redirect(`https://ui-avatars.com/api/?name=${ initials }&${ query }`);
		}
	} catch(e) {

		console.log('Error getting avatar, using fallback:', e);
		res.redirect(`https://ui-avatars.com/api/?name=NA&${ query }`);
	}
};

Clone this wiki locally