diff --git a/.gitmodules b/.gitmodules index 2f9eb3f..6b512ea 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,6 +1,3 @@ [submodule "src/common"] path = src/common url = https://github.com/innervate-ru/common.git -[submodule "dscommon"] - path = dscommon - url = https://github.com/delightsoft/DSCommon3.git diff --git a/config/default.js b/config/default.js new file mode 100644 index 0000000..9a195f1 --- /dev/null +++ b/config/default.js @@ -0,0 +1,28 @@ +module.exports = { + node: 'test', + consoleLevel: 5, + graphql: { + description: 'Включен ли graphIql интерфейс на сервере', + enableUI: true, + pathname: '/graphql' + }, + http: { + protocol: 'http', + hostname: 'localhost', + port: 3000 + }, + postgres: { + host: 'localhost', + port: 5432, + user: 'postgres', + password: '12345', + database: 'postgres', + max: 10, + idleTimeoutMillis: 30000 + }, + externalTestService: {}, + secret: 'UKBKhmHGjyg&^y;ogKUVHMgvmjB u.username === username && u.password === password); + if (user) { + const {password, ...userWithoutPassword} = user; + const token = jwt.sign( + {...userWithoutPassword}, + config.secret, + {expiresIn: '24h'} + ); + return { + ...userWithoutPassword, + token + }; + } +} + +async function getAll() { + return users.map(u => { + const {password, ...userWithoutPassword} = u; + return userWithoutPassword; + }); +} diff --git a/src/api/users/users.controller.js b/src/api/users/users.controller.js new file mode 100644 index 0000000..480bd81 --- /dev/null +++ b/src/api/users/users.controller.js @@ -0,0 +1,21 @@ +const express = require('express'); +const router = express.Router(); +const userService = require('./user.service'); + +// routes +router.post('/authenticate', authenticate); +router.get('/', getAll); + +module.exports = router; + +function authenticate(req, res, next) { + userService.authenticate(req.body) + .then(user => user ? res.json(user) : res.status(400).json({message: 'Username or password is incorrect'})) + .catch(err => next(err)); +} + +function getAll(req, res, next) { + userService.getAll() + .then(users => res.json(users)) + .catch(err => next(err)); +} diff --git a/src/graphqlSchemaV2.js b/src/graphqlSchemaV2.js index 79ce385..9d61e33 100644 --- a/src/graphqlSchemaV2.js +++ b/src/graphqlSchemaV2.js @@ -14,8 +14,8 @@ export default oncePerServices(function (services = missingArgument('services')) const resolvers = Object.create(null); await (new SchemaBuilder({ - test: require('./services/test/graphql').default(services) - + test: require('./services/test/graphql').default(services), + user: require('./services/user/graphql').default(services), }).build({typeDefs, resolvers})); return makeExecutableSchema({ diff --git a/src/index.js b/src/index.js index 5108293..c6cf984 100644 --- a/src/index.js +++ b/src/index.js @@ -12,6 +12,7 @@ import {missingExport} from './common/services' import errorDataToEvent from './common/errors/errorDataToEvent' const schema = require('./index.schema'); const realConsole = console; +// const errorHandler = require('../api/_helpers/error-handler') (async function () { @@ -38,17 +39,25 @@ const realConsole = console; manager = new (require('./common/services').NodeManager(consoleAndBusServicesOnly))({ // далее consoleAndBusServicesOnly нельзя. нужно пользоваться manager.services name: nodeName, services: [ - require('./services/postgres') + require('./services/postgres'), + require('./services/user') ] }); // ждем пока NodeManager скажет что он готов. при этом часть сервисов может быть в состоянии failed await manager.started; - + let expressApp = express(); expressApp.use(cors()); - + // expressApp.use(bodyParser.urlencoded({extended: false})); + // expressApp.use(bodyParser.json()); + + expressApp.use('/', require('./api')); + + expressApp.use(require('./api/_helpers/error-handler')); + + let graphqlRouterV2 = express.Router(); const graphqlSchemaV2 = await (require('./graphqlSchemaV2').default(manager.services)()); graphqlRouterV2.post('/graphql/v2', bodyParser.json(), graphqlExpress(request => ({ @@ -57,7 +66,8 @@ const realConsole = console; }))); graphqlRouterV2.get('/graphql/v2', graphiqlExpress({endpointURL: '/graphql/v2'})); expressApp.use('/', graphqlRouterV2); - + + // Запускаем сервер let httpServer = http.Server(expressApp); await new Promise(function (resolve, reject) { @@ -66,7 +76,7 @@ const realConsole = console; else resolve(data); }) }); - + bus.event({ type: 'webserver.started', service: nodeName, diff --git a/src/services/user/graphql.js b/src/services/user/graphql.js new file mode 100644 index 0000000..4729158 --- /dev/null +++ b/src/services/user/graphql.js @@ -0,0 +1,44 @@ +import {oncePerServices, missingService} from '../../common/services/index' + +const PREFIX = 'User'; + +export default oncePerServices(function (services) { + + const graphqlBuilderSchema = require('../../common/graphql/LevelBuilder.schema'); + + const { + user = missingService('user') + } = services; + + return async function builder(args) { + + graphqlBuilderSchema.build_options(args); + const { parentLevelBuilder, typeDefs, builderContext } = args; + + typeDefs.push(` + + type ${PREFIX}QueryElement { + user_id: Int, + login: String, + email: String, + name: String, + manager: Boolean, + blocked: Boolean, + birthday: String + } + + `); + + parentLevelBuilder.addQuery({ + name: `usersQuery`, + type: `[${PREFIX}QueryElement]`, + args: ` + user_id: Int + `, + resolver: function (args, request) { + return user.getAllUsers(args) + }, + }); + + } +}); diff --git a/src/services/user/index.js b/src/services/user/index.js new file mode 100644 index 0000000..180faeb --- /dev/null +++ b/src/services/user/index.js @@ -0,0 +1,48 @@ +import configApi from 'config'; +import merge from 'lodash/merge'; +import { missingService, oncePerServices, serviceName } from '../../common/services'; + +export const name = serviceName(__filename); + +// const schema = require('./index.schema'); +const serviceConfig = configApi.get('externalTestService'); + +export default oncePerServices(function (services) { + const { + postgres = missingService('postgres') + } = services; + + class UserService { + + _timerId = null; + + constructor(options) { + // schema.ctor_options(this, options); + this._options = options; + } + + async _serviceStart() { + if (this._enabled && this._importEnabled) { + this._timerId = setInterval(() => { + return console.info(`user service is alive`); + }, this._processInterval); + } + + } + + async _serviceStop() { + clearInterval(this._timerId); + } + + async getAllUsers({context}) { + const list = await postgres.exec({ + context, + statement: `SELECT t.*, CTID FROM public.users t LIMIT 501` + }); + return list.rows.map(item => ({...item, birthday: item.data && item.data.birthday})) + } + } + + const mergedConfig = merge(serviceConfig, { dependsOn: [postgres] }); + return new (require('../../common/services').Service(services)(UserService))(name, mergedConfig); +});