Форум программистов, компьютерный форум, киберфорум
GraphQL
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 5.00/4: Рейтинг темы: голосов - 4, средняя оценка - 5.00
0 / 0 / 1
Регистрация: 24.11.2019
Сообщений: 312

Как осуществить мутацию с Graphql

25.04.2021, 20:37. Показов 1013. Ответов 1
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
App.vue
PHP/HTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
<template>
  <div id="app">
    <div style="margin: 0 20% 0 20%">
      <form @submit.prevent="createArticle" enctype="multipart/form-data">
        <h2>Create article</h2>
        <div class="input-field">
          <input id="articleName" type="text" name="title" required placeholder="Article name" v-model="form.title">
        </div>
        <div class="input-field">
        <textarea id="messageArticle" type="text" name="message" required placeholder="Article description"
                  style="resize:vertical;
        min-height:150px" v-model="form.message"
        ></textarea>
        </div>
        <p>
          <label>
            <input name="status_order" id="shipped" type="radio" value="Shipped" v-model="form.status" checked/>
            <span>Shipped</span>
          </label>
        </p>
        <p>
          <label>
            <input name="status_order" id="cancelled" type="radio" value="Cancelled" v-model="form.status"/>
            <span>Cancelled</span>
          </label>
        </p>
        <div>
          <input id="date" type="date" class="datepicker" max="2022-01-09" name="date" required v-model="form.date">
        </div>
        <button  type="submit" class="btn" style="margin-top:20px;">Create</button>
      </form>
 
      <button style="margin-top: 30px" type="submit" @click="getArticles" class="btn">Open Articles</button>
    </div>
    <div style="margin: auto" v-if="articles.length !== 0">
      <table style="margin: auto;width: 730px; margin-top: 20px">
        <tr>
          <th onclick="sortTable(1)">title</th>
          <th onclick="sortTable(2)">Message</th>
          <th onclick="sortTable(3)">Status</th>
          <th onclick="sortTable(4)">Date</th>
        </tr>
        <tr v-for="(article) in articles" v-bind:key="article">
          <td>{{ article.title }}</td>
          <td>{{ article.message }}</td>
          <td>{{ article.status }}</td>
          <td>{{ article.date }}</td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
import axios from 'axios'
 
export default {
  name: 'app',
  data() {
    return {
      showArticlesFlag: false,
      numberArticles: 0,
      form: {
        title: '',
        message: '',
        status: '',
        date: '',
      },
      articles: [],
      newArticle: null
    }
  },
  methods: {
    async createArticle() {
      try {
        const res = await axios.post(
            'http://localhost:4000/graphql', {
              query: `
                  mutation createArticle($title: String!, $message: String!, $status: String!, $date: String!) {
                    createArticle(newTitle: $title, newMessage: $message, newStatus: $status, newDate: $date) {
                      newTitle
                      newMessage
                      newStatus
                      newDate
                }
              }`,
              variables:{
                title: this.form.title,
                message: this.form.message,
                status: this.form.status,
                date: this.form.date,
              }
            })
        this.newArticle = res.data.data
        console.log(this.newArticle)
      } catch (e) {
        console.log('err', e)
      }
    },
    async getArticles() {
      this.numberArticles = 0
      this.showArticlesFlag = true;
      try {
        const res = await axios.post(
            'http://localhost:4000/graphql', {
              query: `{
                getAllArticles {
                  title
                  message
                  status
                  date
                }
               }`
            })
        this.articles = res.data.data.getAllArticles
        console.log(res.data.data.getAllArticles)
      } catch (e) {
        console.log('err', e)
      }
    }
 
  }
}
</script>
index.js
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
const express = require('express')
const {graphql, buildSchema} = require('graphql')
const {graphqlHTTP} = require('express-graphql')
const cors = require('cors')
const bcrypt = require('bcryptjs')
const mongoose = require('mongoose')
 
const Schema = mongoose.Schema;
 
const articleSchema = new Schema({
    title: String,
    message: String,
    status: String,
    date: String,
}, {versionKey: false})
 
const userSchema = new Schema({
    email: {type: String, unique: true, required: true},
    pass: {type: String, unique: true, required: true}
}, {versionKey: false})
 
const articles = mongoose.model("Article", articleSchema)
 
const users = mongoose.model("User", userSchema)
 
const schema = buildSchema(`
    type User {
        email: String
        pass: Int
    }
    type Article {
        title: String
        message: String
        status: String
        date: String
    }
    input UserInput {
        email: String!
        pass: Int!
    }
    input ArticleInput {
        title: String!
        message: String!
        status: String!
        date: String!
    }
    type Query{
        getAllArticles: [Article]
        getUser(email: String) : User
    }
    type Mutation {
        createArticle(title: String!,message: String!,status: String!,date: String!): Article
        createUser(input: UserInput): User
        
    }
`)
const createUser = (input) => {
    const hashPassword = bcrypt.hashSync(input.pass, 4)
    const email = input.email
    return {
        email, hashPassword
    }
}
const createArticle = (input) => {
    console.log("fdsfsd")
    const title = input.title
    const message = input.message
    const status = input.status
    const date = input.date
    return {
        title, message, status, date
    }
}
const rootValue = {
    getAllArticles: () => {
        return articles.find({})
    },
    getUser: ({email}) => {
        return users.findOne(user => user.email === email)
    },
    createUser: ({input}) => {
        const user = createUser(input)
        users.create(user).then(r => {
            console.log(r)
        })
        return user
    },
    createArticle: ({title, message, status, date}) => {
        const article = {title, message, status, date}
        articles.create(article).then(r => {
            console.log(r)
        })
        return article
    }
}
 
const app = express()
app.use(cors())
 
 
app.use(`/graphql`, graphqlHTTP({
    rootValue, schema, graphiql: true
}))
 
 
async function start() {
    try {
        await mongoose.connect('mongodb+srv://dima:1088834@cluster0.uwrbc.mongodb.net/websokets',
            {
                useNewUrlParser: true,
                useUnifiedTopology: true,
                useFindAndModify: false
            }
        )
        app.listen(4000, () => {
            console.log('Server has been started...')
        })
    } catch (e) {
        console.log(e)
    }
}
 
start()
в файле App.vue в функции
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
async createArticle() {
      try {
        const res = await axios.post(
            'http://localhost:4000/graphql', {
              query: `
                  mutation createArticle($title: String!, $message: String!, $status: String!, $date: String!) {
                    createArticle(newTitle: $title, newMessage: $message, newStatus: $status, newDate: $date) {
                      newTitle
                      newMessage
                      newStatus
                      newDate
                }
              }`,
              variables:{
                title: this.form.title,
                message: this.form.message,
                status: this.form.status,
                date: this.form.date,
              }
            })
        this.newArticle = res.data.data
        console.log(this.newArticle)
      } catch (e) {
        console.log('err', e)
      }
    },
я написал мутацию для создания новой статьи, выкидывает ошибку 404 плохой запрос, в чем может быть проблема
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
25.04.2021, 20:37
Ответы с готовыми решениями:

Как осуществить в дельфи осуществить поиск по таблице из другой формы?
Очень выручите, плизз

Создать триггер на мутацию
Помогите пожалуйста создать триггер на мутацию, по лабе нужно сделать, все сделал а этого никак не могу понять как сделать, простенький...

MeteorJS и GraphQL
Привет, Хочу сказать что до недавнего времени MeteorJS и GraphQL являются какойто мутью в голове. И я встречаю людей которые говорят...

1
0 / 0 / 1
Регистрация: 24.11.2019
Сообщений: 312
26.04.2021, 21:58  [ТС]
все равно не могу найти ошибку
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
26.04.2021, 21:58
Помогаю со студенческими работами здесь

graphql mutation
Можете помочь составить мутацию? type Mutation { createCustomMatch(input: CreateCustomMatchInput!): Int } input...

Рассмотреть равномерное скрещивание и двухточечную мутацию
z(x, y)  int( x) int( y), 5.12  x  5.12, 5.12  y  5.12 Рассмотреть равномерное скрещивание и двухточечную мута- цию. Каждая...

GraphQL validation error
..... const app = Relay.createContainer(App, { fragments: { viewer: () =&gt; Relay.QL` fragment on CalendarGames { ...

Ген. алгоритмы. Заменить одноточечную мутацию на двухточечную
У меня есть задача. Есть её решение, исходя из образца с частичной корректировкой под условие. Проблема - в алгоритме прописана функция...

Куда нужно устанавливать GraphQL?
GraphQL пр использовании нужно настраивать только на одной стороне, либо на двух? Допустим, есть сервер, который поддерживает GraphQL,...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
Новые блоги и статьи
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
Ломающие изменения в C#.NStar Alpha
Etyuhibosecyu 20.11.2025
Уже можно не только тестировать, но и пользоваться C#. NStar - писать оконные приложения, содержащие надписи, кнопки, текстовые поля и даже изображения, например, моя игра "Три в ряд" написана на этом. . .
Мысли в слух
kumehtar 18.11.2025
Кстати, совсем недавно имел разговор на тему медитаций с людьми. И обнаружил, что они вообще не понимают что такое медитация и зачем она нужна. Самые базовые вещи. Для них это - когда просто люди. . .
Создание Single Page Application на фреймах
krapotkin 16.11.2025
Статья исключительно для начинающих. Подходы оригинальностью не блещут. В век Веб все очень привыкли к дизайну Single-Page-Application . Быстренько разберем подход "на фреймах". Мы делаем одну. . .
Фото: Daniel Greenwood
kumehtar 13.11.2025
Расскажи мне о Мире, бродяга
kumehtar 12.11.2025
— Расскажи мне о Мире, бродяга, Ты же видел моря и метели. Как сменялись короны и стяги, Как эпохи стрелою летели. - Этот мир — это крылья и горы, Снег и пламя, любовь и тревоги, И бескрайние. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru