Skip to content

Instantly share code, notes, and snippets.

@EndyKaufman
Last active December 8, 2021 10:17
Show Gist options
  • Save EndyKaufman/2ae5ac15c22a440520c7f77fba24170a to your computer and use it in GitHub Desktop.
Save EndyKaufman/2ae5ac15c22a440520c7f77fba24170a to your computer and use it in GitHub Desktop.
SlackModuleDI
export const SLACK_CONFIG = 'SLACK_CONFIG';
export interface SlackConfig {
serviceName: string;
enable?: boolean;
domain: string;
tag: string;
channel: string;
accessToken: string;
}
@Module({
imports: [CustomInjectorModule],
providers: [SlackService],
exports: [CustomInjectorModule, SlackService],
})
class SlackModuleCore {}
@Module({
imports: [SlackModuleCore],
exports: [SlackModuleCore],
})
export class SlackModule {
static forRoot(config: SlackConfig): DynamicModule {
return {
module: SlackModule,
providers: [{ provide: SLACK_CONFIG, useValue: { enable: true, ...config } }],
exports: [SLACK_CONFIG]
};
}
}
@Injectable()
export class SlackService {
private logger = new Logger(SlackService.name);
constructor(private readonly customInjectorService: CustomInjectorService) {}
public send(request: IncomingWebhookSendArguments & { channel?: string }): void {
const config = this.customInjectorService.getLastComponentByName<SlackConfig>('SLACK_CONFIG')!;
if (!config.enable) {
return;
}
const url = 'https://slack.com/api/chat.postMessage';
if (request.attachments) {
if (request.attachments.length > 0 && request.attachments[0].footer) {
if (config.tag) {
request.attachments[0].footer = `${config.serviceName || request.attachments[0].footer} (${config.tag})`;
} else {
request.attachments[0].footer = `${config.serviceName || request.attachments[0].footer}`;
}
} else {
request.attachments[0].footer = config.serviceName ? `${config.serviceName} (${config.tag})` : config.tag;
}
if (request.attachments?.length > 0) {
request.attachments[0].author_name = `<${config.domain}|${config.domain}>`;
}
if (!request.channel) {
request.channel = config.channel;
}
if (!request.icon_emoji && request.attachments?.length > 0 && (request.attachments[0] as any).icon_emoji) {
request.icon_emoji = (request.attachments[0] as any).icon_emoji;
}
if (!request.username && request.attachments?.length > 0 && (request.attachments[0] as any).username) {
request.username = (request.attachments[0] as any).username;
}
}
from(axios.post(url, request, { headers: { authorization: `Bearer ${config.accessToken}` } }))
.pipe(
catchError((err) => {
this.logger.debug(request);
this.logger.error(err, err.stack);
return throwError(() => err);
}),
map((res: AxiosResponse<any>) => res.data),
tap((data: SlackChatPostMessageRequest) => {
if (!data.message) {
this.logger.debug(request);
this.logger.error(data);
}
}),
catchError((err) => {
this.logger.debug(request);
this.logger.error(err, err.stack);
return of(null);
})
)
.subscribe();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment