/home/bdqbpbxa/dev-subdomains/admin.pixory.goodface.com.ua/src/api/my-user/controllers/my-user.ts
import { Context } from 'koa';
import { sanitize } from '@strapi/utils';
import { SanitizeFunc } from '@strapi/utils/dist/sanitize';
import { Model } from '@strapi/utils/dist/types';
import { updateUserSchema } from "../common/update-user-schema";
import { UpdateUserBody } from '../common/update-user-body';
import { UserService } from '../services/user';
export default {
async update(ctx: Context) {
try {
const user = ctx.state.user;
if (!user) {
return ctx.unauthorized('You must be authenticated to update user information');
}
updateUserSchema.validateSync(ctx.request?.body || {});
const body = ctx.request.body as UpdateUserBody;
const supportedCurrencies = await strapi.service('api::configuration.configuration').getAvailableCurrencies()
const supportedCurrenciesUppercase = supportedCurrencies.map(c => c.toUpperCase());
if (body.currency && !supportedCurrenciesUppercase.includes(body.currency?.toUpperCase())) {
return ctx.badRequest(`Currency ${body.currency} is not supported`);
}
const updatedUser = await strapi.db.query('plugin::users-permissions.user').update({
where: { id: user.id },
data: {
...body,
},
populate: {
shipingAddress: { populate: { country: true, state: true } },
billingAddress: { populate: { country: true, state: true } },
projects: true,
orders: true
}
});
const model = strapi.getModel('plugin::users-permissions.user');
const sanitizedUser = await getSanitizer(model).output(updatedUser, model);
return ctx.send({ user: sanitizedUser });
} catch (error) {
strapi.log.error('Error updating user:', error);
return ctx.internalServerError('An error occurred while updating the user');
}
},
async get(ctx: Context) {
try {
const currentUser = ctx.state.user;
if (!currentUser) {
return ctx.unauthorized('You must be authenticated');
}
const userService = new UserService(strapi);
const user = await userService.get(currentUser.id)
const model = strapi.getModel('plugin::users-permissions.user');
const sanitizedUser = await getSanitizer(model).output(user, model);
return ctx.send({ user: sanitizedUser });
} catch (error) {
strapi.log.error('Error fetching user profile:', error);
return ctx.internalServerError('An error occurred while fetching user profile');
}
}
};
function getSanitizer(model: Model): {output: SanitizeFunc} {
return sanitize.createAPISanitizers({
sanitizers: {},
getModel: () => model
})
}