Skip to content

Commit

Permalink
feat: replace Client.authFromCode() with Client.fromAuthCode()
Browse files Browse the repository at this point in the history
`authFromCode()` was a mutating method, which goes against the API
design vision of snoots. It has been replaced with `fromAuthCode()`,
which is a static factory function. This is an important step towards
ensuring the Client object is internally immutable.

BREAKING CHANGE: `Client.authFromCode()` has been replaced with
`Client.fromAuthCode()`.
  • Loading branch information
thislooksfun committed Feb 4, 2022
1 parent ba87fdf commit 8fa90b8
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 12 deletions.
13 changes: 7 additions & 6 deletions examples/oauth/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,14 @@ app.get("/auth", async (req, res) => {
return;
}

// Create a new Reddit client.
const client = new Client({ userAgent, creds });

try {
// Authenticate with the code we were given. Note that the redirectUri here
// MUST match the uri given to `getAuthUrl`, or else this will fail.
await client.authFromCode(code, redirectUri);
// Create a new Client from the given auth code. Note that the redirectUri
// here MUST match the uri given to `getAuthUrl`, or else this will fail.
const client = await Client.fromAuthCode(
{ userAgent, creds },
code,
redirectUri
);

// Get and display the user's information so we know it worked!
const user = await client.users.fetchMe();
Expand Down
26 changes: 20 additions & 6 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -209,20 +209,34 @@ export default class Client {
}

/**
* Authorize this client from an OAuth code.
* Create a client from an OAuth code.
*
* @param opts The Client options.
* @param code The OAuth code.
* @param redirectUri The redirect URI. This ***must*** be the same as the uri
* given to {@link OAuth.getAuthUrl}.
* given to {@link makeAuthUrl}.
*
* @returns A promise that resolves when the authorization is complete.
*/
async authFromCode(code: string, redirectUri: string): Promise<void> {
const creds = this.creds;
static async fromAuthCode<Self extends typeof Client>(
this: Self,
opts: Required<Omit<ClientOptions, "auth">>,
code: string,
redirectUri: string
): Promise<InstanceType<Self>> {
const creds = opts.creds;
if (!creds) throw "No creds";

this.token = await tokenFromCode(code, creds, this.userAgent, redirectUri);
this.auth = { refreshToken: this.token.refresh! };
const client = new this(opts);
client.token = await tokenFromCode(
code,
creds,
client.userAgent,
redirectUri
);
client.auth = { refreshToken: client.token.refresh! };

return client as InstanceType<Self>;
}

/**
Expand Down

0 comments on commit 8fa90b8

Please sign in to comment.