This commit is contained in:
2022-10-10 22:52:40 -06:00
parent f1391bde3d
commit 074021530f
38 changed files with 9315 additions and 0 deletions

View File

@ -0,0 +1,5 @@
// index.d.ts
declare module "*.gql" {
const content: any;
export default content;
}

View File

@ -0,0 +1,21 @@
'use strict';
import { createProductoController, deleteProductoController, getProductosController } from '../../controllers/controllerGraphQL';
// A map of functions which return data for the schema.
const resolvers = {
Query: {
// eslint-disable-next-line
productos: (rootValue, args, context) => getProductosController(),
},
Mutation: {
// eslint-disable-next-line
productosMutation: (rootValue, args, context) => ({}),
},
ProductosMutation: {
insertProducto: (rootValue, args) => createProductoController(rootValue, args),
deleteProducto: (rootValue, args) => deleteProductoController(rootValue, args)
}
};
export default resolvers;

View File

@ -0,0 +1,24 @@
module.exports = `
"""Producto Query"""
type Producto {
id: ID
nombre: String
}
type InsertProductoRes {
producto: Producto
mensaje: String
}
input ProductoInput{
nombre: String
}
"""Esta es la Data de LogIn, Si los datos no son correctos devuelve el usuario Null y la conexion en False"""
type ProductosMutation {
insertProducto(producto: ProductoInput): InsertProductoRes
deleteProducto(id: ID): String
}
`

View File

@ -0,0 +1,17 @@
import { makeExecutableSchema } from '@graphql-tools/schema';
import resolvers from'../resolvers';
import Productos from './Productos.gql';
// The GraphQL schema
const rootTypes = `
type Query {
productos: [Producto]
}
type Mutation {
productosMutation: ProductosMutation
}
`;
const typeDefs = [ rootTypes, Productos ];
export default makeExecutableSchema({typeDefs, resolvers});

View File

@ -0,0 +1,30 @@
'use strict';
import express from 'express'; //express
import { graphqlHTTP } from 'express-graphql';
import { config } from '../../config';
import schema from './schema';
const server = express.Router();//Router de Express
server.use(
'/',
graphqlHTTP( (req, res) => {
return {
schema,
graphiql: config.GRAPHIQL,
context: { req, res }
};
}),
);
// DO NOT DO app.listen() unless we're testing this directly
if (require.main === module) {
server.listen((process.env.PORT || 4000), () => {
console.log(`Iniciando Express en el puerto 4000${server.graphqlPath}`); /*${app.get('port')}*/
});
}
// Instead do export the app:
export default server;

View File

@ -0,0 +1,124 @@
'use strict';
import { ObjectID } from 'mongodb';
import ProductosModel from '../../models';
const { insertProducto, getAllProductos, deleteProducto } = ProductosModel;
//Funcion para insertar un Producto en MongoDB
export const createProductoController = async (rootValue, args) => {
const producto = args.producto;
const promise = new Promise((resolve) => {
const cb = (res, disconnect) => {
//assert.equal(err, null);
//console.log("Found the following records");
console.log(res.insertedId.toString());
resolve({
producto: {
id: res.insertedId.toString(),
...producto
},
mensaje: 'Se inserto exitosamente el Producto'
});
//console.log(res)
disconnect();
};
insertProducto(producto, cb);
});
const result = await promise; // wait till the promise resolves (*)
//console.log(result); // "done!"
return result;
};
//Termina Funcion para insertar un Producto en MongoDB
//Funcion para traer todos los Productos
export const getProductosController = async () => {
const promise = new Promise((resolve) => {
const cb = (err, res, disconnect) => {
if(err){
new Error('No hay registros de Productos');
disconnect();
}else{
const data = res.map( producto => {
const productoReturn = {
...producto,
id: producto._id,
};
delete productoReturn['_id'];
return productoReturn;
});
resolve(data);
disconnect();
}
};
getAllProductos(cb);
});
const result = await promise; // wait till the promise resolves (*)
//console.log(result); // "done!"
return result;
};
//Termina Funcion para traer todos los Productos
//Funcion para Eliminar un Objetivo en MongoDB
export const deleteProductoController = async (rootValue, args) => {
const id = args.id;
const promise = new Promise((resolve) => {
const cb = (res, disconnect) => {
//console.log(res)
if (res) {
//assert.equal(1, res.deletedCount);
resolve(`Se eliminó exitosamente el Producto con id: ${id}`);
disconnect();
} else {
resolve('No se eliminó el Producto');
disconnect();
}
};
deleteProducto(cb, new ObjectID(id));
});
const result = await promise; // wait till the promise resolves (*)
//console.log(result); // "done!"
return result;
};
//Termina Funcion para Eliminar un Objetivo en MongoDB

View File

@ -0,0 +1,84 @@
'use strict';
import ws from 'ws'; // yarn add ws
import express from 'express'; //express
import cors from 'cors';
import cookieParser from 'cookie-parser';
import { useServer } from 'graphql-ws/lib/use/ws';
import { execute, subscribe } from 'graphql';
import GraphQLserver from './GraphQL/server';// Server of GraphQL,
import expressPlayground from 'graphql-playground-middleware-express';
import schema from './GraphQL/schema';
import { config } from '../config';
import apiRouter from './routes';
const app = express(), //creating app
whitelist = config.WHITELIST_URLS,
corsOptions = {
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1 || !origin) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
credentials: true
};
//Inicialization of services of express
app
.use(cookieParser())
.use(express.urlencoded({limit: '500mb', extended: true}))
.use(express.json({limit: '500mb', extended: true}))
.use(cors(corsOptions))
.use(apiRouter)//Routes de App
.use('/graphql', GraphQLserver);//Server of Graphql
if(config.PLAYGROUND_GRAPHQL === true){
app.get('/playground', expressPlayground({ endpoint: '/graphql' }));
}
// DO NOT DO app.listen() unless we're testing this directly
if (require.main === module) {
const server = app.listen(config.PORT, () => {
// create and use the websocket server
const wsServer = new ws.Server({
server,
path: '/graphql',
});
useServer({
schema,
execute,
subscribe,
// eslint-disable-next-line
onConnect: (ctx) => {
//console.log('Connect');
},
// eslint-disable-next-line
onSubscribe: (ctx, msg) => {
//console.log('Subscribe');
},
// eslint-disable-next-line
onNext: (ctx, msg, args, result) => {
//console.debug('Next');
},
// eslint-disable-next-line
onError: (ctx, msg, errors) => {
//console.error('Error');
},
// eslint-disable-next-line
onComplete: (ctx, msg) => {
//console.log('Complete');
},
}, wsServer);
console.log(`Starting Express on port ${config.PORT} and iniciating server of web sockets`);
});
}
// Instead do export the app:
export default app;

View File

@ -0,0 +1,38 @@
/* eslint-disable */
'use strict';
import { MongoClient } from 'mongodb';
import { config } from '../../../../config';
// Connection URL
// eslint-disable-next-line no-useless-escape
const url = `mongodb:\/\/${config.mongoDBConfig.user}:${config.mongoDBConfig.password}@${config.mongoDBConfig.host}:${parseInt(config.mongoDBConfig.port)}`;
const dbName = config.mongoDBConfig.db;
async function connect(cb) {
const client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true })
try{
await client.connect();
console.log('conexion exitosa con mongoDB');
const db = client.db(dbName);
const disconnect = () => {
// Close connection
client.close( ()=>{
console.log('desconexion exitosa con mongoDB');
});
};
await cb(db, disconnect);
}catch(err){
console.log(err.stack);
}
}
export default connect;
/* eslint-enable */

View File

@ -0,0 +1,51 @@
'use strict';
import conn from './config/apiMongoDB-connection';
export const insertProducto = (data, cb) => {
async function callback (db, disconnect) {
// Insert a single document
await db.collection('Productos')
.insertOne(data)
.then( res => cb(res, disconnect));
}
conn(callback);
};
export const getAllProductos = (cb) => {
async function callback(db, disconnect) {
// Insert a single document
await db.collection('Productos')
.find()
.limit(0)
.toArray( (err, res) => {
cb(err, res, disconnect);
});
}
conn(callback);
};
export const deleteProducto = (cb, id) => {
async function callback (db, disconnect) {
// Insert a single document
await db.collection('Productos')
.deleteOne({ _id: id })
.then( res => cb(res, disconnect));
//.updateOne({ _id: data.id }, { $set: { estado: data.estado} })
}
conn(callback);
};

View File

@ -0,0 +1,5 @@
'use strict';
import { insertProducto, getAllProductos, deleteProducto } from './apiMongoDBModel';
export default { insertProducto, getAllProductos, deleteProducto };

View File

@ -0,0 +1,13 @@
'use strict';
// use this to set API REST
import express from 'express';
import bodyParser from 'body-parser';//bodyParser conversionde Api REST,
const apiRouter = express.Router();//Router de Express
apiRouter
.use(bodyParser.json())
.use(bodyParser.urlencoded({extended: false}));
export default apiRouter;