Suggestions on attaching to driver immediately after creating session from plugin

I am hoping to create a plugin that does some device setup immediately following creating a session.

My thought was to add a handler in the plugin for createSession() and within the handler attach to driver from session info returned when calling await next(). This would allow me to do any driver actions on the device as soon as the session is created.

I couldn’t find any examples of doing something similar so figured I’d throw the question out there before giving it a shot. Thanks for any suggestions

You may try to intercept the handler like that. Here we call our stuff before the command, although you could do something like

case 'createSession':
  const originalCreateResult = await next();
  // do my stuff after createSession
  return originalCreateResult;

Thanks @mykola-mokhnach

Is the CreateResult just a mapping? What’s the best way to get an XCUITestDriver instance from the originalCreateResult? Would I have to instantiate a new object by attaching to the session using something like const driver = await attach(opts) (https://webdriver.io/docs/api/modules/#attachattachoptions) or can I access the driver instance some other way?

Ultimately, I’d like to do something like

case 'createSession':
      const originalCreateResult = await next();
      // get driver instance from result
      // const driver = new XCUITestDriver(originalCreateResult);
      // do stuff with driver
      const element = await driver.find_element(...);

It probably won’t work this way. Ig you need to get the created driver instance then it is necessary to fetch the session identifier from the originalCreateResult and then retrieve the original driver object from the sessions property of the umbrella driver.
See https://github.com/appium/appium/blob/aa5ae9a8cad0aae33bbe9b114db3f1e93dbe8bc8/packages/appium/lib/appium.js#L186
and https://github.com/appium/appium/blob/aa5ae9a8cad0aae33bbe9b114db3f1e93dbe8bc8/packages/appium/lib/appium.js#L249

Thanks @mykola-mokhnach, I was able to get it to working following those examples!