Commit 86d0b0f5 authored by diegolmello's avatar diegolmello
Browse files

- Stop logging errors (causes red screens on React Native)

- Fixed `on` method
- Added `setBaseUrl` at api.js
- Changed bundle location to dist/index.js instead of dist/bundle.js
parent 105de1f3
This diff is collapsed.
......@@ -27,6 +27,7 @@ export declare const host: string;
* Hard code endpoint prefix, because all syntax depends on this version
*/
export declare const url: string;
export declare function setBaseUrl(host: string): void;
/** Convert payload data to query string for GET requests */
export declare function getQueryString(data: any): string;
/** Setup default headers with empty auth for now */
......
/// <reference types="lru-cache" />
import LRU from 'lru-cache';
/** @TODO: Remove ! post-fix expression when TypeScript #9619 resolved */
export declare let instance: any;
......
......@@ -46,9 +46,14 @@ export interface ICallback {
/** Credentials for login method */
export interface ICredentials {
password: string,
password?: string,
username?: string,
email?: string,
ldap?: boolean,
ldapOptions?: object
ldapOptions?: object,
totp?: boolean,
code?: number,
resume?: string,
crowd?: boolean,
oauth?: any
}
......@@ -30,19 +30,28 @@ export function loggedIn (): boolean {
/** Initialise configs */
export const host = settings.host
function getUrl (host: string) {
return ((host.indexOf('http') === -1)
? host.replace(/^(\/\/)?/, 'http://')
: host) + '/api/v1/'
}
/**
* Prepend protocol (or put back if removed from env settings for driver)
* Hard code endpoint prefix, because all syntax depends on this version
*/
export const url = ((host.indexOf('http') === -1)
? host.replace(/^(\/\/)?/, 'http://')
: host) + '/api/v1/'
export const url = getUrl(host)
/** Initialize client */
const client = axios.create({
baseURL: url
})
export function setBaseUrl (host: string) {
client.defaults.baseURL = getUrl(host)
}
/** Convert payload data to query string for GET requests */
export function getQueryString (data: any) {
if (!data || typeof data !== 'object' || !Object.keys(data).length) return ''
......@@ -118,8 +127,7 @@ export async function post (
logger.debug('[API] POST result:', result)
return result.data
} catch (err) {
console.error(err)
logger.error(`[API] POST error (${endpoint}):`, err)
throw new Error(`[API] POST error (${endpoint}): ${ err }`)
}
}
......@@ -147,7 +155,7 @@ export async function get (
logger.debug('[API] GET result:', result)
return result.data
} catch (err) {
logger.error(`[API] GET error (${endpoint}):`, err)
throw new Error(`[API] GET error (${endpoint}): ${ err }`)
}
}
......@@ -176,8 +184,7 @@ export async function put (
logger.debug('[API] PUT result:', result)
return result.data
} catch (err) {
console.error(err)
logger.error(`[API] PUT error (${endpoint}):`, err)
throw new Error(`[API] PUT error (${endpoint}): ${ err }`)
}
}
......@@ -206,8 +213,7 @@ export async function del (
logger.debug('[API] DELETE result:', result)
return result
} catch (err) {
console.error(err)
logger.error(`[API] DELETE error (${endpoint}):`, err)
throw new Error(`[API] DELETE error (${endpoint}): ${ err }`)
}
}
......
......@@ -84,7 +84,7 @@ export class EventEmitter {
try {
listener.apply(this, args)
} catch (err) {
logger.error(`[ddp] event emit error: ${err.message}`)
// logger.error(`[ddp] event emit error: ${err.message}`)
}
})
}
......@@ -153,8 +153,8 @@ export default class Socket extends EventEmitter {
this.on('pong', handlePong)
this.on('ping', handlePing)
this.on('result', (data: any) => this.ddp.emit(data.id, { id: data.id, result: data.result, error: data.error }))
this.on('ready', (data: any) => this.ddp.emit(data.subs[0], data))
this.on('result', (data: any) => this.emit(data.id, { id: data.id, result: data.result, error: data.error }))
this.on('ready', (data: any) => this.emit(data.subs[0], data))
// this.on('error', () => this.reconnect())
this.on('disconnected', debounce(() => this.reconnect(), 300))
......@@ -175,7 +175,7 @@ export default class Socket extends EventEmitter {
})
this._connect().catch(e => {
logger.error(`[ddp] connection error: ${e.message}`)
// logger.error(`[ddp] connection error: ${e.message}`)
})
}
......@@ -230,10 +230,10 @@ export default class Socket extends EventEmitter {
if (ignore) {
return
}
const cancel = this.ddp.once('disconnected', reject)
this.ddp.once(id, (data: any) => {
const cancel = this.once('disconnected', reject)
this.once(id, (data: any) => {
this.lastPing = new Date()
this.ddp.removeListener('disconnected', cancel)
this.removeListener('disconnected', cancel)
return (data.error ? reject(data.error) : resolve({ id, ...data }))
})
})
......@@ -254,7 +254,7 @@ export default class Socket extends EventEmitter {
delete this.connection
}
} catch (err) {
logger.error(`[ddp] disconnect error: ${err.message}`)
// logger.error(`[ddp] disconnect error: ${err.message}`)
}
}
......@@ -274,7 +274,6 @@ export default class Socket extends EventEmitter {
this.connection.onopen = () => {
this.emit('open')
resolve()
this.ddp.emit('open')
return this._login && this.login(this._login)
}
......@@ -289,7 +288,7 @@ export default class Socket extends EventEmitter {
this.emit(data.msg, data)
return data.collection && this.emit(data.collection, data)
} catch (err) {
logger.error(`[ddp] EJSON parse error: ${e.message}`)
// logger.error(`[ddp] EJSON parse error: ${e.message}`)
}
}
})
......@@ -327,7 +326,7 @@ export default class Socket extends EventEmitter {
try {
await this._connect()
} catch (err) {
logger.error(`[ddp] reconnect error: ${err.message}`)
// logger.error(`[ddp] reconnect error: ${err.message}`)
}
}, 1000)
}
......@@ -342,7 +341,10 @@ export default class Socket extends EventEmitter {
return this.send({
msg: 'method', method, params
}).catch((err) => {
logger.error(`[ddp] call error: ${err.message}`)
// logger.error(`[ddp] call error: ${err.message}`)
if (err && /you've been logged out by the server/i.test(err.reason)) {
this.emit('forbidden');
}
return Promise.reject(err)
})
}
......@@ -361,7 +363,7 @@ export default class Socket extends EventEmitter {
msg: 'unsub',
id
}).then((data: any) => data.result || data.subs).catch((err) => {
logger.error(`[ddp] unsubscribe error: ${err.message}`)
// logger.error(`[ddp] unsubscribe error: ${err.message}`)
return Promise.reject(err)
})
}
......@@ -387,7 +389,7 @@ export default class Socket extends EventEmitter {
this.subscriptions[id] = args
return args
}).catch((err) => {
logger.error(`[ddp] subscribe error: ${err.message}`)
// logger.error(`[ddp] subscribe error: ${err.message}`)
return Promise.reject(err)
})
}
......
......@@ -155,9 +155,9 @@ function setupMethodCache (ddp: Socket): void {
*/
export function asyncCall (method: string, ...params: any[]): Promise <any> {
logger.info(`[${method}] Calling (async): ${JSON.stringify(params)}`)
return Promise.resolve(ddp.call(method, ...params))
return ddp.call(method, ...params)
.catch((err: Error) => {
logger.error(`[${method}] Error:`, err)
// logger.error(`[${method}] Error:`, err)
throw err // throw after log to stop async chain
})
.then(({ result }: any) => {
......@@ -189,7 +189,7 @@ export function callMethod (name: string, params?: any | any[]): Promise<any> {
export function cacheCall (method: string, key: string): Promise<any> {
return methodCache.call(method, key)
.catch((err: Error) => {
logger.error(`[${method}] Error:`, err)
// logger.error(`[${method}] Error:`, err)
throw err // throw after log to stop async chain
})
.then((result: any) => {
......@@ -215,6 +215,26 @@ export function login (credentials: ICredentials = {
login = ddp.login(
{ ldap: true, ldapOptions: credentials.ldapOptions || {}, ldapPass: credentials.password, username: credentials.username }
)
} else if (credentials.crowd) {
logger.info(`[login] Logging in ${credentials.username} with CROWD`)
login = ddp.login({ crowd: true, username: credentials.username, crowdPassword: credentials.password })
} else if (credentials.totp) {
logger.info(`[login] Logging in ${credentials.username} with TOTP`)
login = ddp.login({
totp: {
login: {
user: { username: credentials.username, email: credentials.email },
password: credentials.password
},
code: credentials.code
}
})
} else if (credentials.resume) {
logger.info(`[login] Logging in with resume token`)
login = ddp.login({ resume: credentials.resume })
} else if (credentials.oauth) {
logger.info(`[login] Logging in with OAuth`)
login = ddp.login({ oauth: credentials.oauth })
} else {
logger.info(`[login] Logging in ${credentials.username}`)
login = ddp.login({
......@@ -236,7 +256,7 @@ export function login (credentials: ICredentials = {
/** Logout of Rocket.Chat via Socket */
export function logout (): Promise<void | null> {
return ddp.logout().catch((err: Error) => {
logger.error('[Logout] Error:', err)
// logger.error('[Logout] Error:', err)
throw err // throw after log to stop async chain
})
}
......@@ -266,7 +286,7 @@ export function unsubscribe (subscription: Subscription): void {
subscriptions.splice(index, 1) // remove from collection
logger.info(`[${subscription.id}] Unsubscribed`)
}).catch((err: Error) => {
logger.error('[Unsubscribe] Error:', err)
// logger.error('[Unsubscribe] Error:', err)
throw err
})
}
......@@ -285,18 +305,8 @@ export function subscribeToMessages (): Promise<Subscription> {
}
export function on (collection: string, callback: ICallback): void {
logger.info(`[reactive] Listening for change events in collection ${collection}`)
ddp.on(collection, (obj: any) => {
const changedMessage = obj.fields
if (changedMessage && changedMessage.args.length > 0) {
if (Array.isArray(changedMessage.args)) {
logger.info(`[received] Message in room ${changedMessage.args[0].rid}`)
callback(null, changedMessage.args[0], changedMessage.args[1])
} else {
logger.debug('[received] Update without message args')
}
} else {
logger.debug('[received] Reactive query at ID ${ _id } without results')
}
ddp.on(collection, (result: object) => {
callback(null, result)
})
}
/**
......@@ -353,14 +363,14 @@ export function respondToMessages (
) {
promise = joinRooms(config.rooms)
.catch((err) => {
logger.error(`[joinRooms] Failed to join configured rooms (${config.rooms.join(', ')}): ${err.message}`)
// logger.error(`[joinRooms] Failed to join configured rooms (${config.rooms.join(', ')}): ${err.message}`)
})
}
lastReadTime = new Date() // init before any message read
reactToMessages(async (err, message, meta) => {
if (err) {
logger.error(`[received] Unable to receive: ${err.message}`)
// logger.error(`[received] Unable to receive: ${err.message}`)
callback(err) // bubble errors back to adapter
}
......@@ -425,7 +435,7 @@ export async function joinRoom (room: string): Promise<void> {
let roomId = await getRoomId(room)
let joinedIndex = joinedIds.indexOf(room)
if (joinedIndex !== -1) {
logger.error(`[joinRoom] room was already joined`)
// logger.error(`[joinRoom] room was already joined`)
} else {
await asyncCall('joinRoom', roomId)
joinedIds.push(roomId)
......@@ -437,7 +447,7 @@ export async function leaveRoom (room: string): Promise<void> {
let roomId = await getRoomId(room)
let joinedIndex = joinedIds.indexOf(room)
if (joinedIndex === -1) {
logger.error(`[leaveRoom] failed because bot has not joined ${room}`)
// logger.error(`[leaveRoom] failed because bot has not joined ${room}`)
} else {
await asyncCall('leaveRoom', roomId)
delete joinedIds[joinedIndex]
......
......@@ -17,7 +17,7 @@ module.exports = {
extensions: [ '.ts', '.js' ]
},
output: {
filename: 'bundle.js',
filename: 'index.js',
library: 'RocketChat',
libraryTarget: 'umd',
path: path.resolve(__dirname, 'dist/')
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment