# Interview
## Task 1
Check for errors
```
const helper = require('@mongoHelper');
module.exports = (botId, entityId) => {
const bot = await helper.Bot.findOne({ botId }).exec();
const entity = helper.Entity.findOne({ entityId }).exec();
const project = helper.Project.findOne({ projectId: bot.projectId }).exec();
return { bot, entity, project };
};
```
## Task 2
What will be logged
```
const config = { template: { a: { v: 1 } } };
const { template: { a: org } } = config;
const { template: { a: copy } } = config;
org.v+=1;
console.log(org.v) =>
console.log(copy.v) =>
console.log(config.template.a.v) =>
```
## Task 3
Write function to check if number is simple
const num1 = 7; // true
const num2 = 8; // false
```
```
## Task 4
Write function to check if array is sorted
isSorted([1,2,5,7,34]) => true
isSorted([1,56,2,5,7,34]) => false
isSorted([4,3,2,1]) => true
```
```
## Task 5
Write next function
Input: aaabbcdaa
Output:
3 a
2 b
1 c
1 d
2 a
```
```
## Task 6
Write function to check if word is palindrome
const word1 = 'rotator'; // true
const word2 = 'palindrome'; // false
```
```
## Task 7
Write next function
Input: 2 5 4 6
Output:
4 5 6
2 8 10 12
3 12 15 18
4 16 20 24
5 20 25 30
## Task 8
```
const types = [
{ id: 1, name: 'type-1' },
{ id: 2, name: 'type-2' },
{ id: 3, name: 'type-3' }
];
// const enumTypes = {
// 'type-1': 1,
// 'type-2': 2,
// 'type-3': 3
// }
```
## Task 9
```
function intersection(a, b) {
}
```
intersection([1,2,3], [2,3,5]) => [2,3]
## Task 10
distinct([1,2,3,4,1,2,2,4,-6]) => [1,2,3,4,-6]
```
```
## Task 11
```
app.get('/sessions', handlers.getSessions);
app.get('/sessions/:sessionId', handlers.getSessions.byId);
app.listen(3000);
dbConnect().then(async () => {
const config = await helper.SystemConfig();
setSystemConfig(config);
process.env.isOnline = 'true';
// app.on('service-online', () => {})
app.emit('service-online');
})
```
## Task 12
```
users = { _id, userId, email, password };
tasks = { _id, taskId, userId, content, expirationDateTime };
```
1. Написати запит, який буде повертати усіх користувачів в яких є таски
3. Написати запит, який буде повертати усіх користувачів в яких є таски, котрі не заекспайрилися
4. Написати запит, який буде повертати усі таски які не заекспайрилися, разом з користувачами, яким вони належать
5. Написати запит, який буде повертати список користувачів у яких заекспайрилися всі таски
## Task 13
Create API route for creating and updating task object in DB. Task object:
```
{
taskId: number, // this field will be created by DB
userId: number,
name: string,
notes: string[],
}
```
post: /tasks body: { userId, name }
put: /tasks/:taskId body: { name, notes }
Function for DB:
* helper.task.create(data) - this function creating object and return Promise
* helper.task.updateOne(query, data) - this function updating object and return Promise
* helper.task.find(query)
```
const express = require('express');
const app = express();
app.listen(3000);
```
## Task 14
```
const handler = (cb) => {
helper.Entity.findOne(
{ entityId: 45 },
(err,data)=> {
if (err) { return cb(err); }
helper.FileEntity.find(
{ ownerEntityId: data._id },
(err, files) => {
if (err) { return cb(err); }
return cb(null, { entities: data, files })
}
)
}
)
}
```
## Task 15
Create report with first 5 session what was in [167, 392]. Get entity docs for each entity who are in session and get types names.
Collection sessions:
```=json
{
"_id" : ObjectId("6093d4c3cdf9a3000a7cb5c5"),
"allowPosting" : {
"roleIds" : [ ],
"entityIds" : [ ]
},
"conversationFlow" : [
"directMessaging"
],
"nextStep" : [ ],
"isFake" : false,
"isActive" : true,
"updatedAt" : ISODate("2021-05-06T11:46:07.000Z"),
"settings" : {
"endSessionMessage" : {
"isEnabled" : false,
"platforms" : [ ]
},
"_id" : ObjectId("6093d4c3cdf9a3000a7cb5c4")
},
"lastMessageDateTime" : ISODate("2021-05-06T11:46:07.552Z"),
"workspaceId" : 167,
"typeId" : 0,
"sessionTtl" : 31536000000,
"entities" : [
{
"isInitiator" : false,
"originalEntityIds" : [ ],
"isMute" : false,
"isRemoved" : false,
"_id" : ObjectId("6093d4c3cdf9a3000a7cb5c6"),
"entityId" : 329162,
"platformId" : 8,
"platformConnectorId" : "5dfc1d5e0bba7a000729aea0"
},
{
"isInitiator" : true,
"originalEntityIds" : [ ],
"isMute" : false,
"isRemoved" : false,
"_id" : ObjectId("6093d4c3cdf9a3000a7cb5c7"),
"entityId" : 809540,
"platformId" : 8,
"platformConnectorId" : "5dfc1d5e0bba7a000729aea0"
}
],
"instanceId" : "00c61b117c0aedd9e59e512a9456b92e5fd9f0d78f74ed0cbc3f9dfa167d15b12d1f025f9e37a6ef2b9c1e33b5cbfecb5bc353bf5d26592f51a2335eee5ccdd4b34ce006ce40ebcc",
"startDateTime" : ISODate("2021-05-06T11:36:35.996Z"),
"expirationDateTime" : ISODate("2022-05-06T11:46:08.735Z"),
"sessionId" : 496004,
"__v" : 2,
"messagesCount" : 2
},
```
Collection entities:
```=json
{
"_id" : ObjectId("609283eccdf9a3000a7cb13d"),
"platformPriority" : [ ],
"organizationIds" : [
3
],
"entityTypeIds" : [
0
],
"email" : "kkarpp@gmail.com",
"lastName" : "Karp",
"firstName" : "Customer neew",
"phoneNumber" : "+xxxxxxxxxxxx",
"createdAt" : ISODate("2021-05-05T11:39:24.980Z"),
"updatedAt" : ISODate("2021-05-05T11:39:24.981Z"),
"entityId" : 809664,
"__v" : 0
},
```
Collection entityTypes:
```=json
{
"_id" : ObjectId("5b69f25984d8e645dcdb7396"),
"entityTypeId" : 4,
"isMergeEligible" : false,
"name" : "Rake System User"
},
```
Result:
```=json
{
"_id" : ObjectId("5dfc1d80f2bc5500075f5b81"),
"sessionId" : 13654,
"sessionStatus" : true,
"entities" : [
{
"_id" : ObjectId("5cda74e83f9e1f0006c3827a"),
"entityId" : 2007,
"entityTypes" : [
"Rake System User"
],
"name" : "Oleh2Buhaienko"
}
]
},
```
# Task 16
input: sessions-inactivity_1995
output:
```
{ event: 'session-inactivity', value: 1995 }
```
input: message-watcher_1979-3452
output:
```
{ event: 'message-watcher', value: [1979, 3452] }
```
```
```
# Task 17
RegExp
"Session with id {{sessionId}} has ended. Agent name: {{agentName}}"
```
const transform = (str, tokens) => {
}
const message= { text: "Session with id {{sessionId}} has ended. Agent name: {{agentName}}" };
const tokens = {
sessionId: 56,
agentName: 'Max',
sentAt: '2021-05-07T11:43:31.836Z'
};
const text = transform(message.text, tokens);
```
# Task 18
Options:
- Move validation to middleware
- Use Joi modules
```
app.post('/user', (req,res) => {
const { email, password } = req.body;
if (!email) {
return res.sttus(400).send({ message: 'Email is required' });
}
if (!password) {
return res.sttus(400).send({ message: 'Password is required' });
}
return handler.createUser(req, res);
})
```
# Task 19
Request logger
```
app.get('/users/:userId', async (req,res) => {
const user = await helper.Users.findOne({ userId: + req.params.userId});
return res.status(200).send(user);
})
```
Output:
```
[req:ffda1464-c39c-11eb-8529-0242ac130003][path:/users/56][method:get]
[req:ffda1464-c39c-11eb-8529-0242ac130003][time:2.3s] response: { userId: 56, firstName: 'FN', lastName: 'LN' }
```