typedi#Service TypeScript Examples
The following examples show how to use
typedi#Service.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Client.ts From ts-discord-bot-boilerplate with MIT License | 6 votes |
@Service()
export class Client extends DiscordClient implements BotClient {
public settings: BotSettings;
constructor(private actionManager: ActionManager) {
super(configuration.clientOptions || {});
this.settings = configuration;
this.settings.token = process.env.BOT_TOKEN;
this.initialize();
}
private async initialize(): Promise<void> {
try {
this.actionManager.initializeCommands(this);
this.actionManager.initializeEvents(this);
await this.login(configuration.token);
} catch (e) {
Logger.error(`Could not initialize bot: ${e}`);
}
}
public get commands(): Collection<string, Command> {
return this.actionManager.commands;
}
}
Example #2
Source File: Lua.resolver.ts From ExpressLRS-Configurator with GNU General Public License v3.0 | 6 votes |
@Service()
@Resolver()
export default class LuaResolver {
constructor(private luaService: LuaService) {}
@Query(() => LuaScript)
async luaScript(
@Args() args: LuaArgs,
@Arg('gitRepository') gitRepository: GitRepository
): Promise<LuaScript> {
const fileLocation = await this.luaService.loadLuaScript(
args,
gitRepository
);
return { fileLocation };
}
}
Example #3
Source File: ServerProfile.ts From sakeperp-arbitrageur with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Service()
export class ServerProfile {
private readonly log = Log.getLogger(ServerProfile.name)
readonly web3Endpoint: string
readonly arbitrageurPK: string
readonly cexApiKey: string
readonly cexApiSecret: string
readonly cexApiPassword: string
readonly cexSubaccount: string | undefined
readonly cexPlatform: string
readonly emailUser: string
readonly emailPass: string
readonly emailTo: string
readonly emailHost: string
readonly emailPort: string
constructor() {
this.web3Endpoint = process.env.WEB3_ENDPOINT!
this.arbitrageurPK = process.env.ARBITRAGEUR_PK!
this.cexApiKey = process.env.CEX_API_KEY!
this.cexApiSecret = process.env.CEX_API_SECRET!
this.cexApiPassword = process.env.CEX_API_PASSWORD!
this.cexSubaccount = process.env.CEX_SUBACCOUNT
this.cexPlatform = process.env.CEX_PLATFORM!
this.emailUser = process.env.EMAIL_USER!
this.emailPass = process.env.EMAIL_PASSWORD!
this.emailTo = process.env.EMAIL_TO!
this.emailHost = process.env.EMAIL_HOST!
this.emailPort = process.env.EMAIL_PROT!
this.log.jinfo({
event: "ServerProfile",
params: {
web3Endpoint: this.web3Endpoint,
}
})
}
}
Example #4
Source File: CashSplitSumRepository.ts From cashcash-desktop with MIT License | 6 votes |
@Service()
@EntityRepository(CashSplitSum)
export default class CashSplitSumRepository extends Repository<CashSplitSum> {
async findCustom(parameters: TransactionDatabaseParameters): Promise<CashSplitSum[]> {
let qb = this.createQueryBuilder('s');
qb = QueryBuilderUtil.addDateFilter(
qb,
's',
'createdDate',
parameters.createdDateFrom,
parameters.createdDateTo,
);
qb = QueryBuilderUtil.addDateFilter(
qb,
's',
'updatedDate',
parameters.updatedDateFrom,
parameters.updatedDateTo,
);
if (parameters.accountIdList && parameters.accountIdList.length > 0) {
qb = qb.andWhere(`s.accountId IN ( ${parameters.accountIdList.join(', ')} )`);
}
if (parameters.currencyIdList && parameters.currencyIdList.length > 0) {
qb = qb.andWhere(`s.currencyId IN ( ${parameters.currencyIdList.join(', ')} )`);
}
return await qb.getMany();
}
async deleteAll(): Promise<DeleteResult> {
return await this.createQueryBuilder().delete().execute();
}
}
Example #5
Source File: index.ts From TXQ with MIT License | 6 votes |
@Service('merchantapilogModel')
class MerchantapilogModel {
constructor(@Inject('db') private db: ContextFactory) {}
public async save(accountContext: IAccountContext, miner: string, eventType: string, response: any, txid?: string): Promise<string> {
const client = await this.db.getClient(accountContext);
const restext = JSON.stringify(response);
let requestTypeStr = eventType ? eventType : '';
let result: any = await client.query(`
INSERT INTO merchantapilog(miner, txid, event_type, response)
VALUES ($1, $2, $3, $4)
RETURNING id`, [ miner, txid ? txid : null, requestTypeStr, restext ],
);
return result.rows[0].id;
}
}
Example #6
Source File: game-service.ts From monopoly with MIT License | 6 votes |
@Service()
export class GameService {
constructor(private gameRepository: GameRepository) {}
createGame(id: string, game: IGame) {
this.gameRepository.save(id, new Game(game));
}
updateGame(id: string, game: Game) {
this.gameRepository.save(id, game);
}
getGame(id: string) {
return this.gameRepository.findById(id);
}
hasGame(id: string) {
return Boolean(this.gameRepository.findById(id));
}
hasFreeGame(id: string) {
return this.gameRepository.findById(id)?.hasFreeSlot();
}
save() {
this.gameRepository.saveToFile();
}
}
Example #7
Source File: mailer.ts From nodejs-typescript-graphql-starter with MIT License | 6 votes |
@Service()
export default class MailerService {
Logger: Logger;
constructor(@Inject('emailClient') private emailClient) {
this.Logger = Container.get('logger');
}
public async SendWelcomeEmail(email) {
/**
* @TODO Call Mailchimp/Sendgrid or whatever
*/
// Added example for sending mail from mailgun
this.Logger.debug(`?Sending Welcome mail to %o`, email);
const data = {
from: 'Excited User <[email protected]>',
to: email,
subject: 'Hello',
text: 'Testing some Mailgun awesomness!',
};
this.emailClient.messages().send(data);
return { delivered: 1, status: 'ok' };
}
public StartEmailSequence(sequence: string, user: Partial<IUser>) {
if (!user.email) {
throw new Error('No email provided');
}
// @TODO Add example of an email sequence implementation
// Something like
// 1 - Send first email of the sequence
// 2 - Save the step of the sequence in database
// 3 - Schedule job for second email in 1-3 days or whatever
// Every sequence can have its own behavior so maybe
// the pattern Chain of Responsibility can help here.
return { delivered: 1, status: 'ok' };
}
}
Example #8
Source File: AccessTokenService.ts From spurtcommerce with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Service()
export class AccessTokenService {
constructor(@OrmRepository() private accessTokenRepository: AccessTokenRepository,
@Logger(__filename) private log: LoggerInterface) {
}
public findOne(accessToken: any): Promise<any> {
return this.accessTokenRepository.findOne(accessToken);
}
// delete token
public async delete(id: number): Promise<any> {
this.log.info('Delete a token');
await this.accessTokenRepository.delete(id);
return;
}
// create token
public async create(accessToken: any): Promise <AccessToken> {
return this.accessTokenRepository.save(accessToken);
}
}
Example #9
Source File: ActionManager.ts From ts-discord-bot-boilerplate with MIT License | 5 votes |
@Service()
export class ActionManager {
public commands: Collection<string, Command> = new Collection<string, Command>();
/**
* Parses files into commands from the configured command path.
* @param {BotClient} client The original client, for access to the configuration.
* @returns {Collection<string, Command>} A dictionary of every command in a [name, object] pair.
*/
public initializeCommands(client: BotClient): void {
const { commands } = client.settings.paths;
readdir(commands, (err, files) => {
if (err) Logger.error(err);
files.forEach(cmd => {
if (statSync(join(commands, cmd)).isDirectory()) {
this.initializeCommands(client);
} else {
const Command: any = require(join(
__dirname,
'../../',
`${commands}/${cmd.replace('ts', 'js')}`
)).default;
const command = new Command(client);
this.commands.set(command.conf.name, command);
}
});
});
}
/**
* Initializes every event from the configured event path.
* @param {BotClient} client The original client, for access to the configuration.
*/
public initializeEvents(client: BotClient): void {
const { events } = client.settings.paths;
readdir(events, (err, files) => {
if (err) Logger.error(err);
files.forEach(evt => {
const Event: any = require(join(
__dirname,
'../../',
`${events}/${evt.replace('ts', 'js')}`
)).default;
const event = new Event(client);
const eventName = evt.split('.')[0];
client.on(
eventName.charAt(0).toLowerCase() + eventName.slice(1),
(...args: string[]) => event.run(args)
);
});
});
}
}
Example #10
Source File: Firmware.resolver.ts From ExpressLRS-Configurator with GNU General Public License v3.0 | 5 votes |
@Service()
@Resolver()
export default class FirmwareResolver {
constructor(
private firmwareService: FirmwareService,
private userDefinesBuilder: UserDefinesBuilder,
private targetsLoaderService: TargetsLoader
) {}
@Query(() => [Device])
async availableFirmwareTargets(
@Args() args: TargetArgs,
@Arg('gitRepository') gitRepository: GitRepository
): Promise<Device[]> {
return this.targetsLoaderService.loadTargetsList(args, gitRepository);
}
@Query(() => [UserDefine])
async targetDeviceOptions(
@Args() args: TargetDeviceOptionsArgs,
@Arg('gitRepository') gitRepository: GitRepository
): Promise<UserDefine[]> {
return this.userDefinesBuilder.build(args, gitRepository);
}
@Mutation(() => BuildFlashFirmwareResult)
async buildFlashFirmware(
@Arg('input') input: BuildFlashFirmwareInput,
@Arg('gitRepository') gitRepository: GitRepository
): Promise<BuildFlashFirmwareResult> {
return this.firmwareService.buildFlashFirmware(
input,
gitRepository.url,
gitRepository.srcFolder
);
}
@Mutation(() => ClearPlatformioCoreDirResult)
async clearPlatformioCoreDir(): Promise<ClearPlatformioCoreDirResult> {
try {
await this.firmwareService.clearPlatformioCoreDir();
return new ClearPlatformioCoreDirResult(true);
} catch (e) {
return new ClearPlatformioCoreDirResult(
false,
`Failed to clear platformio state: ${e}`
);
}
}
@Mutation(() => ClearFirmwareFilesResult)
async clearFirmwareFiles(): Promise<ClearFirmwareFilesResult> {
try {
await this.firmwareService.clearFirmwareFiles();
return new ClearFirmwareFilesResult(true);
} catch (e) {
return new ClearFirmwareFilesResult(
false,
`Failed to clear firmware files cache: ${e}`
);
}
}
@Subscription(() => BuildProgressNotification, {
topics: [PubSubTopic.BuildProgressNotification],
})
buildProgressNotifications(
@Root() n: BuildProgressNotificationPayload
): BuildProgressNotification {
return new BuildProgressNotification(n.type, n.step, n.message);
}
@Subscription(() => BuildLogUpdate, {
topics: [PubSubTopic.BuildLogsUpdate],
})
buildLogUpdates(@Root() u: BuildLogUpdatePayload): BuildLogUpdate {
return new BuildLogUpdate(u.data);
}
}
Example #11
Source File: AuthService.ts From jaebook-server with MIT License | 5 votes |
@Service()
export class AuthService {
constructor(@InjectRepository() private userRepository: UserRepository) {}
/**
* 사용자 정보가 유효한지 확인하고 유효하면 사용자 정보를 반환한다.
* @param loginUserDto 사용자 로그인 DTO
*/
public async validateUser(loginUserDto: LoginUserDto): Promise<User> {
const user = await this.userRepository.findOne({
select: ["id", "realName", "email", "password"],
where: {
email: loginUserDto.email,
},
});
if (user) {
const isPasswordMatch = await user.comparePassword(loginUserDto.password);
if (isPasswordMatch) {
return user;
}
}
return undefined;
}
/**
* RefreshToken이 일치하는 사용자 정보를 반환한다.
* @param userId 사용자 Id
* @param refreshToekn RefreshToken
*/
public async validateUserToken(
userId: string,
refreshToekn: string,
): Promise<User> {
const user = await this.userRepository.findOne({
select: ["id", "realName", "email"],
where: {
id: userId,
refreshToekn: refreshToekn,
},
});
if (user) {
return user;
}
return undefined;
}
/**
* RefreshToken을 사용자에게 저장한다.
* @param user User
* @param token RefreshToken
*/
public async saveRefreshToken(user: User, token: string): Promise<void> {
user.refreshToekn = token;
await this.userRepository.save(user);
}
}
Example #12
Source File: ERC20Service.ts From sakeperp-arbitrageur with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Service()
export class ERC20Service {
private readonly log = Log.getLogger(ERC20Service.name)
constructor(readonly ethService: EthService, readonly systemMetadataFactory: SystemMetadataFactory) {}
private createErc20Contract(tokenAddr: string, from?: Wallet): ERC20Token {
return this.ethService.createContract<ERC20Token>(tokenAddr, ERC20TokenArtifact, from)
}
async allowance(tokenAddr: string, ownerAddr: string, spenderAddr: string): Promise<Big> {
const token = this.createErc20Contract(tokenAddr)
const scaledAmount = await token.functions.allowance(ownerAddr, spenderAddr)
return this.fromScaled(tokenAddr, scaledAmount[0])
}
async approve(
tokenAddr: string,
spenderAddr: string,
amount: Big,
from: Wallet,
overrides?: Overrides,
): Promise<void> {
const token = this.createErc20Contract(tokenAddr, from)
const scaledAmount = await this.toScaled(tokenAddr, amount)
const tx = await token.functions.approve(spenderAddr, scaledAmount, {
...overrides,
})
const receipt = await tx.wait()
if (receipt.status !== 1) throw new Error(`transferError:${tx.hash}`)
}
async balanceOf(tokenAddr: string, accountAddr: string): Promise<Big> {
const token = this.createErc20Contract(tokenAddr)
const scaledAmount = await token.functions.balanceOf(accountAddr)
return this.fromScaled(tokenAddr, scaledAmount[0])
}
async transfer(tokenAddr: string, recipientAddr: string, amount: Big, from: Wallet): Promise<void> {
const token = this.createErc20Contract(tokenAddr, from)
const scaledAmount = await this.toScaled(tokenAddr, amount)
const tx = await token.functions.transfer(recipientAddr, scaledAmount)
const receipt = await tx.wait()
if (receipt.status !== 1) throw new Error(`transferError:${tx.hash}`)
}
// noinspection JSMethodCanBeStatic
async fromScaled(tokenAddr: string, val: BigNumber): Promise<Big> {
const token = this.createErc20Contract(tokenAddr)
const decimals = await token.functions.decimals()
return new Big(ethers.utils.formatUnits(val, decimals[0]))
}
// noinspection JSMethodCanBeStatic
async toScaled(tokenAddr: string, val: Big): Promise<ethers.BigNumber> {
const token = this.createErc20Contract(tokenAddr)
const decimals = await token.functions.decimals()
return ethers.utils.parseUnits(val.toFixed(decimals[0]), decimals[0])
}
}
Example #13
Source File: CashAccountRepository.ts From cashcash-desktop with MIT License | 5 votes |
@Service()
@EntityRepository(CashAccount)
export default class CashAccountRepository extends Repository<CashAccount> {
async findCustom(parameters: AccountParameters): Promise<CashAccount[]> {
let qb = this.createQueryBuilder('a');
qb = this.createWhereClause(qb, parameters);
return await qb.getMany();
}
private createWhereClause<T extends WhereExpression>(
qb: T,
parameters: AccountParameters = simpleAccountParameters,
): T {
qb = QueryBuilderUtil.addDateFilter(
qb,
'a',
'createdDate',
parameters.createdDateFrom,
parameters.createdDateTo,
);
qb = QueryBuilderUtil.addDateFilter(
qb,
'a',
'updatedDate',
parameters.updatedDateFrom,
parameters.updatedDateTo,
);
if (parameters.accountIdList && parameters.accountIdList.length > 0) {
qb = qb.andWhere(`a.id IN ( ${parameters.accountIdList.join(', ')} )`);
}
if (parameters.currencyIdList && parameters.currencyIdList.length > 0) {
qb = qb.andWhere(`a.currencyId IN ( ${parameters.currencyIdList.join(', ')} )`);
}
if (parameters.accountTypeList && parameters.accountTypeList.length > 0) {
qb = qb.andWhere(
`a.type IN ( ${parameters.accountTypeList.map((item) => `'${item}'`).join(', ')} )`,
);
}
if (parameters.isLeaf) {
qb = qb.andWhere(`a.isDirectory = 0`);
}
if (parameters.searchString) {
qb = qb.andWhere(`a.name LIKE %${parameters.searchString}%`);
}
return qb;
}
}
Example #14
Source File: index.ts From TXQ with MIT License | 5 votes |
@Service('auxModel')
class TxModel {
constructor(@Inject('db') private db: Pool) {}
}
Example #15
Source File: game-repository.ts From monopoly with MIT License | 5 votes |
@Service()
export class GameRepository {
cache: GameMap = {};
constructor() {
this.deserialize();
}
findById(id: string): Game | undefined {
return this.cache[id];
}
save(id: string, game: Game) {
this.cache[id] = game;
this.saveToFile();
}
deserialize() {
const gameMap: GameMap = {};
const parsed: { [key: string]: IGame } = JSON.parse(this.readFromFile());
Object.keys(parsed).forEach((key) => {
gameMap[key] = new Game(parsed[key]);
});
this.cache = gameMap;
}
readFromFile() {
try {
const db = fs.readFileSync('db.json', 'utf8');
return db;
} catch (error) {
return '{}';
}
}
saveToFile() {
const raw = JSON.stringify(this.cache);
fs.writeFile('db.json', raw, (error) => {
if (error) {
console.error(error);
}
});
}
}
Example #16
Source File: BannerService.ts From spurtcommerce with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Service()
export class BannerService {
constructor(@OrmRepository() private bannerRepository: BannerRepository,
@Logger(__filename) private log: LoggerInterface) {
}
// create banner
public async create(banner: any): Promise<any> {
this.log.info('Create a new banner ');
return this.bannerRepository.save(banner);
}
// find Condition
public findOne(banner: any): Promise<any> {
return this.bannerRepository.findOne(banner);
}
// update banner
public update(banner: any): Promise<any> {
return this.bannerRepository.save(banner);
}
// banner List
public list(limit: any, offset: any, select: any = [], search: any = [], whereConditions: any = [], count: number | boolean): Promise<any> {
const condition: any = {};
if (select && select.length > 0) {
condition.select = select;
}
condition.where = {};
if (whereConditions && whereConditions.length > 0) {
whereConditions.forEach((item: any) => {
condition.where[item.name] = item.value;
});
}
if (search && search.length > 0) {
search.forEach((table: any) => {
const operator: string = table.op;
if (operator === 'where' && table.value !== undefined) {
condition.where[table.name] = table.value;
} else if (operator === 'like' && table.value !== undefined) {
condition.where[table.name] = Like('%' + table.value + '%');
}
});
}
if (limit && limit > 0) {
condition.take = limit;
condition.skip = offset;
}
condition.order = {
position: 'ASC',
createdDate: 'DESC',
};
if (count) {
return this.bannerRepository.count(condition);
} else {
return this.bannerRepository.find(condition);
}
}
// delete banner
public async delete(id: number): Promise<any> {
return await this.bannerRepository.delete(id);
}
}