lexica-dialog-core
Version:
Core server for Lexica dialog agent.
113 lines • 3.71 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const lodash_1 = require("lodash");
const immutable_1 = require("immutable");
const uuid = require("uuid");
class DefaultSessionService {
constructor(sessionRepository, uni, senderId, expireInMs) {
this.sessionRepository = sessionRepository;
this.uni = uni;
this.senderId = senderId;
this.expireInMs = expireInMs;
}
async init() {
if (lodash_1.isNil(this.session)) {
await this.findOrCreate();
}
}
async save() {
this.session.memories = this.session.memories
.map(memory => {
memory.expire = memory.expire - 1;
return memory;
})
.filter(memory => memory.expire > 0);
if (!lodash_1.isNil(this.session.lastOptions)) {
this.session.lastOptions = this.session.lastOptions.map(sessionOption => {
sessionOption.liveCount += 1;
return sessionOption;
});
}
await this.sessionRepository.save(this.uni, this.senderId, this.session, this.expireInMs);
}
getSessionId() {
return this.session.id;
}
addMemory(intent, features) {
let expire = lodash_1.defaultTo(intent.sessionExpire, -1);
expire = expire + 1;
this.session.memories.push({
expire,
features: features.toObject(),
intent,
});
}
getMemoriesFeatures() {
return this.session.memories.reduce((features, memory) => features.merge(immutable_1.Map(memory.features)), immutable_1.Map());
}
getIntentMemoryFeatures() {
return immutable_1.List(this.session.memories.map(memory => ({
command: memory.intent.command,
features: memory.features,
})));
}
startConversation(intent, features) {
if (this.hasConversation()) {
throw new Error('Already in conversation');
}
this.session.conversation = {
features: features.toObject(),
intent,
};
}
hasConversation() {
return !lodash_1.isNil(this.session.conversation);
}
getConversationIntent() {
if (lodash_1.isNil(this.session.conversation)) {
throw new Error('No conversation');
}
return this.session.conversation.intent;
}
getConversationFeatures() {
if (lodash_1.isNil(this.session.conversation)) {
throw new Error('No conversation');
}
return immutable_1.Map(this.session.conversation.features);
}
updateConversationFeatures(features) {
if (lodash_1.isNil(this.session.conversation)) {
throw new Error('No conversation');
}
this.session.conversation.features = features.toObject();
}
endConversation() {
delete this.session.conversation;
}
setOptions(options) {
this.session.lastOptions = options;
}
hasOptions() {
return !lodash_1.isNil(this.session.lastOptions);
}
getOptions() {
if (lodash_1.isNil(this.session.lastOptions)) {
throw new Error('No options');
}
return this.session.lastOptions;
}
removeOptions() {
delete this.session.lastOptions;
}
async findOrCreate() {
this.session = await this.sessionRepository.findByUniAndSenderId(this.uni, this.senderId);
if (lodash_1.isNil(this.session)) {
this.session = {
id: uuid.v4(),
memories: [],
};
}
}
}
exports.default = DefaultSessionService;
//# sourceMappingURL=SessionService.js.map