Olga_Brekhuntsova 2 éve
szülő
commit
a4de73452e

+ 104 - 0
hw-js-16-graphQL/.gitignore

@@ -0,0 +1,104 @@
+# Logs
+logs
+*.log
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*
+lerna-debug.log*
+
+# Diagnostic reports (https://nodejs.org/api/report.html)
+report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
+
+# Runtime data
+pids
+*.pid
+*.seed
+*.pid.lock
+
+# Directory for instrumented libs generated by jscoverage/JSCover
+lib-cov
+
+# Coverage directory used by tools like istanbul
+coverage
+*.lcov
+
+# nyc test coverage
+.nyc_output
+
+# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
+.grunt
+
+# Bower dependency directory (https://bower.io/)
+bower_components
+
+# node-waf configuration
+.lock-wscript
+
+# Compiled binary addons (https://nodejs.org/api/addons.html)
+build/Release
+
+# Dependency directories
+node_modules/
+jspm_packages/
+
+# TypeScript v1 declaration files
+typings/
+
+# TypeScript cache
+*.tsbuildinfo
+
+# Optional npm cache directory
+.npm
+
+# Optional eslint cache
+.eslintcache
+
+# Microbundle cache
+.rpt2_cache/
+.rts2_cache_cjs/
+.rts2_cache_es/
+.rts2_cache_umd/
+
+# Optional REPL history
+.node_repl_history
+
+# Output of 'npm pack'
+*.tgz
+
+# Yarn Integrity file
+.yarn-integrity
+
+# dotenv environment variables file
+.env
+.env.test
+
+# parcel-bundler cache (https://parceljs.org/)
+.cache
+
+# Next.js build output
+.next
+
+# Nuxt.js build / generate output
+.nuxt
+dist
+
+# Gatsby files
+.cache/
+# Comment in the public line in if your project uses Gatsby and *not* Next.js
+# https://nextjs.org/blog/next-9-1#public-directory-support
+# public
+
+# vuepress build output
+.vuepress/dist
+
+# Serverless directories
+.serverless/
+
+# FuseBox cache
+.fusebox/
+
+# DynamoDB Local files
+.dynamodb/
+
+# TernJS port file
+.tern-port

+ 12 - 0
hw-js-16-graphQL/.prettierrc.json

@@ -0,0 +1,12 @@
+{
+    "printWidth": 80,
+    "tabWidth": 2,
+    "useTabs": false,
+    "semi": true,
+    "singleQuote": true,
+    "trailingComma": "all",
+    "bracketSpacing": true,
+    "jsxBracketSameLine": false,
+    "arrowParens": "avoid",
+    "proseWrap": "always"
+  }

+ 3 - 0
hw-js-16-graphQL/.vscode/settings.json

@@ -0,0 +1,3 @@
+{
+  "liveServer.settings.port": 5502
+}

+ 3 - 0
hw-js-16-graphQL/README.md

@@ -0,0 +1,3 @@
+Все результаты в консоли.
+
+Хостинг http://hw_js_16.olgapistryak.fe.a-level.com.ua/

+ 18 - 0
hw-js-16-graphQL/index.css

@@ -0,0 +1,18 @@
+* {
+  box-sizing: border-box;
+}
+
+body {
+  padding: 30px;
+  text-align: center;
+}
+.wrapper {
+  border: solid rgb(54, 47, 47) 3px;
+  padding: 10px;
+  width: 100px;
+  margin-left: auto;
+  margin-right: auto;
+  background-color: lightgray;
+  border-radius: 5px;
+  margin-bottom: 20px;
+}

+ 16 - 0
hw-js-16-graphQL/index.html

@@ -0,0 +1,16 @@
+<!DOCTYPE html>
+<html>
+
+<head>
+  <meta charset="utf-8">
+  <meta name="viewport" content="width=device-width">
+  <title>hw-js-16-graphQL</title>
+  <!-- <link href="index.css" rel="stylesheet" type="text/css" /> -->
+ </head>
+
+<body>
+  <script src="/js/graphQL.js" ></script>
+  
+</body>
+
+</html>

+ 103 - 0
hw-js-16-graphQL/js/graphQL.js

@@ -0,0 +1,103 @@
+// ДЗ: допилить:
+const getGQL = url =>
+    (query, variables) => fetch(url, {
+        //метод
+        method: 'POST',
+        headers: {
+            //заголовок content-type
+            "Content-Type": "application/json"
+        },
+        body: JSON.stringify({ query, variables })
+        //body с ключами query и variables
+        
+    }).then(res => res.json()).then(data => {
+        //расковырять data, если все ок - отдать data.login или data.
+        // CategoryFindOne, или шо там еще
+        //если есть errors и нет data, то выбросить исключение и тем самым зареджектить промис
+        return data
+    });
+
+const gql = getGQL('http://shop-roles.asmer.fs.a-level.com.ua/graphql');
+// console.log((await gql(`
+//     query NameForMe1($login:String, $password:String){
+//         login(login:$login, password:$password)
+//     }
+// `, { login: 'tst', password: '123' })).data.login)
+
+// написать тестовых запросов:
+// логин, регистрация, категории все, категория по id, товар по id
+// Регистрация
+async function gqlRegistration(login, password) {
+    try {
+        let result = await gql(`mutation register ($login:String, $password:String)
+        {UserUpsert(user:{login:$login, password:$password, nick:$login}) {_id}}`,
+            { "login": login, "password": password });
+        return (result.errors?result.errors[0].message:result.data.UserUpsert._id);
+    }
+    catch (e) { e}
+};
+
+ // Авторизация
+async function gqlLogin(login, password) {
+    try {
+        let result = await gql(`query log ($login:String, $password:String)
+  { login(login:$login, password:$password)}`,
+            { "login": login, "password": password }); 
+                  
+        return (result.data.login?result.data.login:'Пользователь не найден')
+    }
+       catch(e) {e}   
+};
+// Все категории
+async function gqlCats() {
+    try {
+        let result = await gql(`
+  query cats($q:String){
+    CategoryFind(query:$q){_id name parent {
+      _id
+      createdAt
+      name
+    }}
+    }`, {"q": "[{}]"});
+                return (!result.errors?result.data:result.errors[0].message)
+    }
+       catch(e) {e}   
+};
+  
+//Категория по id
+async function gqlCatById(catId) {
+    try {
+        const catIdQ = `[{"_id":"${catId}"}]`;
+        let result = await gql(`query catById($catId:String){
+    CategoryFindOne(query:$catId)
+    {_id name parent{name} subCategories{name}
+    }}`,
+            { "catId": catIdQ });
+                return (!result.errors?result.data:result.errors[0].message)
+    }
+       catch(e) {e}   
+};
+//Товар по id
+async function gqlGoodById(goodId) {
+    try {
+        const goodIdQ = `[{"_id":"${goodId}"}]`;
+        let result = await gql(`query goodById($goodId:String){
+      GoodFindOne(query:$goodId)
+      {_id name price owner{nick}
+    }}`,
+            { "goodId": goodIdQ });
+                return (!result.errors?result.data:result.errors[0].message)
+    }
+       catch(e) {e}   
+};
+
+
+console.log(gqlLogin("Olyatest3", "000"));
+console.log(gqlLogin("OlyaBrekh", "arriba"));
+console.log(gqlRegistration("OlyaBrekh", "arriba"));
+console.log(gqlCats());
+console.log(gqlCatById("5dc4b2553f23b553bf3540fc"));
+console.log(gqlGoodById("5dc45c3d5df9d670df48cc4a"));
+
+
+