<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Проблема с дублированием данных при вызове return вместо reply.send - Fastify]]></title><description><![CDATA[<p dir="auto">Кароче столкнулся с такой проблемой, если вызываю в функции <strong>retrun newUser</strong> за место <strong>reply.send</strong>, то в БД данные отправляются 2 раза, тем самым создавая в моем случае дубликат пользователя.</p>
<p dir="auto">Хотя мне в принципе return и нахой не нужен, но все равно интересно почему так.<img src="https://forum.exlends.ru/assets/plugins/nodebb-plugin-emoji/emoji/android/1f644.png?v=1bd9ff6b60a" class="not-responsive emoji emoji-android emoji--face_with_rolling_eyes" style="height:23px;width:auto;vertical-align:middle" title=":face_with_rolling_eyes:" alt="🙄" /></p>
<pre><code class="language-ts">const createNewUser = async (request: FastifyRequest, reply: FastifyReply) =&gt; {
    const user = request.body;
    const userRepository = AppDataSource.manager.getRepository(User);

    try {
        userRepository.save(user).then((newUser) =&gt; {
            reply.status(201).send({ message: "User created successfully", });
            // ТУТ
            return newUser;
        }).catch((err) =&gt; {
            console.error("Error creating new user:", err);
            reply.status(500).send({ message: "Internal server error" });
        });
    } catch (error) {
        console.error("Database query error:", error);
        reply.status(500).send({ message: "Internal server error" });
    }
}
</code></pre>
]]></description><link>https://forum.exlends.ru/topic/33/problema-s-dublirovaniem-dannyh-pri-vyzove-return-vmesto-reply-send-fastify</link><generator>RSS for Node</generator><lastBuildDate>Wed, 20 May 2026 09:13:41 GMT</lastBuildDate><atom:link href="https://forum.exlends.ru/topic/33.rss" rel="self" type="application/rss+xml"/><pubDate>Sun, 03 Nov 2024 14:21:21 GMT</pubDate><ttl>60</ttl><item><title><![CDATA[Reply to Проблема с дублированием данных при вызове return вместо reply.send - Fastify on Wed, 06 Nov 2024 09:22:20 GMT]]></title><description><![CDATA[<p dir="auto">Кароче как оказалось проблема была в <strong>preHandler</strong>, у меня в роутинге к регистрации юзера была валидация body:</p>
<pre><code class="language-ts">fastifyInstance.post("/users/register", { preHandler: validateCreateUser }, createNewUser);
</code></pre>
<p dir="auto">В итоге я убрал <strong>preHandler</strong>, а логи валидации перенес в сервисы.</p>
]]></description><link>https://forum.exlends.ru/post/75</link><guid isPermaLink="true">https://forum.exlends.ru/post/75</guid><dc:creator><![CDATA[kirilljsx]]></dc:creator><pubDate>Wed, 06 Nov 2024 09:22:20 GMT</pubDate></item><item><title><![CDATA[Reply to Проблема с дублированием данных при вызове return вместо reply.send - Fastify on Tue, 05 Nov 2024 14:49:32 GMT]]></title><description><![CDATA[<p dir="auto">Пользователь @kirilljs написал в <a href="/post/73">Проблема с дублированием данных при вызове return вместо reply.send - Fastify</a>:</p>
<blockquote>
<p dir="auto">const userService = new UserService();</p>
</blockquote>
<p dir="auto">Лучше не создавать сервис каждый раз в функции, это лишние затраты</p>
]]></description><link>https://forum.exlends.ru/post/74</link><guid isPermaLink="true">https://forum.exlends.ru/post/74</guid><dc:creator><![CDATA[Aladdin]]></dc:creator><pubDate>Tue, 05 Nov 2024 14:49:32 GMT</pubDate></item><item><title><![CDATA[Reply to Проблема с дублированием данных при вызове return вместо reply.send - Fastify on Tue, 05 Nov 2024 14:19:39 GMT]]></title><description><![CDATA[<p dir="auto">@Jspi Бля, я кароче переписал уже это очко, теперь функция выглядит так:</p>
<pre><code class="language-ts">const createNewUser = async (request: FastifyRequest, reply: FastifyReply) =&gt; {
    try {
        const userService = new UserService();
        const newUser = await userService.createUser(request.body);
        reply.status(201).send(newUser);
    } catch (error) {
        console.error("Error creating user:", error);
        reply.status(400).send({ message: error.message });
    }
}
</code></pre>
<p dir="auto">Сервис вытащил отдельным слоем, без then:</p>
<pre><code class="language-ts">async createUser(userData: Partial&lt;User&gt;): Promise&lt;User&gt; {
        const existingUser = await this.userRepository.findOneByEmail(userData.email);
        if (existingUser) {
            throw new Error('User with this email already exists.');
        }
        
        const user = new User();
        Object.assign(user, userData);
        return this.userRepository.save(user);
    }
</code></pre>
]]></description><link>https://forum.exlends.ru/post/73</link><guid isPermaLink="true">https://forum.exlends.ru/post/73</guid><dc:creator><![CDATA[kirilljsx]]></dc:creator><pubDate>Tue, 05 Nov 2024 14:19:39 GMT</pubDate></item><item><title><![CDATA[Reply to Проблема с дублированием данных при вызове return вместо reply.send - Fastify on Tue, 05 Nov 2024 12:26:30 GMT]]></title><description><![CDATA[<p dir="auto">Во первых ты  описал <code>createNewUser()</code> как асинхронную функцию,  и она у тебя ничего не возвращает, а также  ты нигде  await  не используешь,  у тебя тогда и try  не будет  ничего ловить</p>
<p dir="auto">Попробуй вместо <code>userRepository.save(user)</code> написать асинхронную функцию простую (например таймер), и сделай там  console.log(), посмотри   сколько сообщений выдаст,  сделай  такой дебаггинг</p>
]]></description><link>https://forum.exlends.ru/post/72</link><guid isPermaLink="true">https://forum.exlends.ru/post/72</guid><dc:creator><![CDATA[Aladdin]]></dc:creator><pubDate>Tue, 05 Nov 2024 12:26:30 GMT</pubDate></item></channel></rss>