123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241 |
- // // получение объекта из jwt токена
- // const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOnsiaWQiOiI2MWE0ZGIyOWM3NTBjMTJiYTZiYTQwMjIiLCJsb2dpbiI6ImVxd2VxZXdldyIsImFjbCI6WyI2MWE0ZGIyOWM3NTBjMTJiYTZiYTQwMjIiLCJ1c2VyIl19LCJpYXQiOjE2MzgxOTQ1NzZ9.Pi1GO6x7wdNrIrUKCQT-32-SsqmgFY-oFDrrXmw74-8'
- // JSON.parse(atob(token.split('.')[1]))
- // // получение контрольных сумм
- // let qqq = 'fdhfakfalfjskgfsdadasdasdasdasdadfsdfkarieqfowerdaesfa'
- // function checkSum(str) {
- // let res = 0
- // for (let letter of str) {
- // res += letter.charCodeAt()
- // }
- // return res
- // }
- // console.log(checkSum(qqq))
- // // добавление соли (секретная последовательность) к информации
- // // для формирования уникальной контрольной суммы
- // function sign(data, salt) {
- // const json = JSON.stringify(data)
- // const sum = checkSum(json + salt)
- // return json + sum
- // }
- // function verify(signed, salt) {
- // const json = signed.slice(0, signed.lastIndexOf('}') + 1)
- // const tokenSum = + signed.slice(signed.lastIndexOf('}') + 1)
- // const sum = checkSum(json + salt)
- // console.log(json, tokenSum, sum)
- // return sum === tokenSum
- // }
- // добавить заголовок Authorization если в localStorage есть authToken (не забудьте слово Bearer и пробел после него.
- // Таким образом все запросы будут уходить не анонимно если в localStorage есть токен.
- const getGQL = (url) => (
- (query, variables) => fetch(url, {
- method: 'POST',
- headers: {
- "Content-Type": "application/json",
- ...(localStorage.authToken ? {Authorization: "Bearer " + localStorage.authToken} : {})
- },
- body: JSON.stringify({query, variables})
-
- }).then(res => res.json()).then(async (data) => {
- if ('errors' in data) {
- // return Promise.reject(new Error('ОШИБКА'))
- throw new Error('ОШИБКА!!!!' + JSON.stringify(data.errors))
- } else {
- return data.data[Object.keys(data.data)[0]]
- }
- })
- );
- const gql = getGQL('http://shop-roles.asmer.fs.a-level.com.ua/graphql');
- // написать функции по типу:
- // для логина, регистрации, а так же для остальных страниц будущего сайта, которые вам пришли на ум.
- function login(log, pass) {
- return gql(`query log($login: String, $password: String) {
- login(login: $login, password: $password)
- }
- `, {login: log, password: pass})
- }
- function register(log, pass) {
- return gql(`mutation reg2($user:UserInput) {
- UserUpsert(user:$user) {
- _id login
- }
- }
- `, {user: {login: log, password: pass}})
- }
- function findUsers(_id = '') {
- return gql(`query userFind {
- UserFind(query: "[{}]") {
- login
- nick
- _id
- }
- }
- `, {query: JSON.stringify([{_id}])})
- }
- function catById(_id) {
- return gql(`query catById($query:String) {
- CategoryFindOne(query:$query) {
- name goods{
- _id name images{
- url
- }
- }
- subCategories {
- _id name
- }
- }
- }`, {query: JSON.stringify([{_id}])})
- }
- function cats() {
- return gql(`query cats($query: String) {
- CategoryFind(query: $query) {
- _id name
- goods {
- name
- images {
- url
- }
- }
- }
- }`, {query: JSON.stringify([{}])})
- }
- function goodById(_id) {
- return gql(`query goodById($q: String) {
- GoodFindOne(query: $q) {
- _id name price description images {
- url
- }
- }
- }`, {q: JSON.stringify([{_id}])})
- }
- function orders() {
- return gql(`query o($query: String) {
- OrderFind(query:$query){
- _id orderGoods{
- price count total good{
- name categories{
- name
- }
- }
- }
- owner {
- _id login
- }
- }
- }`, {query: JSON.stringify([{}])})
- }
- // function ordersByUserId(_id) {
- // return gql(`query oUser($query: String) {
- // OrderFind(query:$query){
- // _id orderGoods{
- // price count total good{
- // name categories{
- // name
- // }
- // }
- // }
- // owner {
- // _id login
- // }
- // }
- // }`,
- // {query: JSON.stringify([
- // {owner: {_id}}
- // ])})
- // }
- function newOrder(_id, count) {
- return gql(`mutation newOrder($q: OrderInput){
- OrderUpsert(order: $q)
-
- {
- _id total
- }
- }`, {q: {
- orderGoods:[
- {count, good:{_id}},
- // {count: count, good:{_id}}
- ]
- }})
- }
-
- ;
- (async function() {
- let allUsers = await findUsers()
- console.log(allUsers)
- let token1 = await login('tst', '123')
- console.log(token1)
- if (typeof jwtDecode(token1) === 'object') {
- localStorage.authToken = token1
- }
- // console.log(await register('zzaa', 'zzaa'))
- let cat = await catById("5dc45acf5df9d670df48cc48")
- console.log(cat)
- let allCats = await cats()
- console.log(allCats)
- let good = await goodById('5dcad3606d09c45440d14d10')
- console.log(good)
- let ord = await orders()
- console.log(ord)
-
- let newOrd = await newOrder('5dcad3606d09c45440d14d10', 5)
- console.log(newOrd)
- })();
- function jwtDecode(token) {
- try {
- let decoded = JSON.parse(atob(token.split('.')[1]))
- return decoded
- } catch (err) {
- console.log(err)
- }
- }
|