123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8" />
- <meta http-equiv="X-UA-Compatible" content="IE=edge" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title>Document</title>
- </head>
- <body>
- <script>
- const getGQL = (url) => {
- return async (query, variables = {}) => {
- let params = { headers: { "Content-Type": "application/json" } };
- let authToken = localStorage.getItem("authToken");
- if (authToken) {
- params.headers.Authorization = "Bearer " + authToken;
- }
- params.body = JSON.stringify({
- query: query,
- variables: variables,
- });
- params.method = "POST";
- let res = await fetch(url, params).then((res) => res.json());
- if ("data" in res) {
- return res.data[Object.keys(res.data)[0]];
- } else if ("errors" in res) {
- throw res.errors[Object.keys(res.errors)[0]];
- }
- };
- };
- const catByID = async (id) => {
- const gql = getGQL("http://shop-roles.asmer.fs.a-level.com.ua/graphql?");
- let catDataOrError = await gql(
- `
- query catByID($q:String){
- CategoryFindOne(query:$q){
- name
- createdAt
- }
- }
- `,
- {
- q: `[{ \"_id\": \"${id}\" }]`,
- }
- );
- return catDataOrError;
- };
- const goodByID = async (id) => {
- const gql = getGQL("http://shop-roles.asmer.fs.a-level.com.ua/graphql?");
- let goodDataOrError = await gql(
- `
- query goodByID($q:String){
- GoodFindOne(query:$q){
- name
- createdAt
- description
- price
- }
- }
- `,
- {
- q: `[{ \"_id\": \"${id}\" }]`,
- }
- );
- return goodDataOrError;
- };
- const register = async (login, password) => {
- localStorage.removeItem("authToken");
- const gql = getGQL("http://shop-roles.asmer.fs.a-level.com.ua/graphql?");
- let respOrError = await gql(
- `mutation register($login:String,$password:String){
- UserUpsert(user:{login:$login,password:$password}){
- _id login
- }
- }`,
- {
- login: login,
- password: password,
- }
- );
- return respOrError;
- };
- const login = async (login, password) => {
- const gql = getGQL("http://shop-roles.asmer.fs.a-level.com.ua/graphql?");
- localStorage.removeItem("authToken");
- const token = await gql(
- `query log($login:String,$password:String){
- login(login:$login,password:$password)
- }
- `,
- {
- login: login,
- password: password,
- }
- );
- localStorage.setItem("authToken", token);
- return token;
- };
- catByID("5dc49f4d5df9d670df48cc64").then((data) => console.log(data));
- goodByID("61714b33ef4e1b3e3b67703a").then((data) => console.log(data));
- </script>
- </body>
- </html>
|