Skip to content

Commit

Permalink
service binding .fetch
Browse files Browse the repository at this point in the history
  • Loading branch information
chientrm committed Jul 18, 2023
1 parent 35bcef1 commit 0190115
Show file tree
Hide file tree
Showing 5 changed files with 105 additions and 7 deletions.
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ Enable Cloudflare Workers runtime for local development.

### D1Database

```ts
import { createD1 } from 'cf-workers-proxy';
```

| Function | Status |
| ----------- | ------ |
| `prepare()` ||
Expand All @@ -38,6 +42,10 @@ Enable Cloudflare Workers runtime for local development.

### Email Routing

```ts
import { sendEmail } from 'cf-workers-proxy';
```

```ts
sendEmail = async (data : {
seb?: SendEmail; // Platform binding object
Expand All @@ -52,6 +60,17 @@ sendEmail = async (data : {
})
```

### Service Bindings

```ts
import { createServiceBinding } from 'cf-workers-proxy';
```

| Function | Status |
| ----------- | ------ |
| `fetch()` ||
| `connect()` ||

## Contributing

Just pull request 😐
3 changes: 3 additions & 0 deletions src/factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { D1DatabaseExecProxy } from './proxies/d1_database/exec/proxy';
import { D1DatabasePreparedStatementAllProxy } from './proxies/d1_database/prepared_statement/all/proxy';
import { D1DatabasePreparedStatementFirstProxy } from './proxies/d1_database/prepared_statement/first/proxy';
import { D1DatabasePreparedStatementRunProxy } from './proxies/d1_database/prepared_statement/run/proxy';
import { FetcherFetchProxy } from './proxies/fetcher/fetch/proxy';
import { SendEmailProxy } from './proxies/send_email/proxy';

class ProxyFactory {
Expand All @@ -19,6 +20,8 @@ class ProxyFactory {
return new D1DatabaseExecProxy({ name, payload });
case SendEmailProxy.proxyType:
return new SendEmailProxy({ name, payload });
case FetcherFetchProxy.proxyType:
return new FetcherFetchProxy({ name, payload });
default:
throw new Error('Unknown proxy type.');
}
Expand Down
36 changes: 36 additions & 0 deletions src/proxies/fetcher/fetch/proxy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { Proxy } from '../../proxy';

interface Payload {
path: string;
method?: string;
body: string;
}

class FetcherFetchProxy extends Proxy<Payload> {
static readonly proxyType = 'FetcherFetchProxy';
constructor({
host,
name,
payload,
}: {
host?: string;
name: string;
payload: Payload;
}) {
const proxyType = FetcherFetchProxy.proxyType;
super({ proxyType, host, name, payload });
}
async execute(env: any): Promise<any> {
const { name } = this,
{ path, body, method } = this.payload,
fetcher = env[name] as Fetcher,
result = await fetcher.fetch(path, {
body,
method,
headers: { 'content-type': 'application/json' },
});
return result;
}
}

export { FetcherFetchProxy };
34 changes: 34 additions & 0 deletions src/proxies/fetcher/proxy_holder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { ProxyHolder } from '../proxy_holder';
import { FetcherFetchProxy } from './fetch/proxy';

interface Payload {}

class FetcherProxyHolder extends ProxyHolder<Payload> implements Fetcher {
async fetch(
input: RequestInfo<unknown, CfProperties<unknown>>,
init?: RequestInit<CfProperties<unknown>> | undefined
): Promise<Response> {
const { host, name } = this,
path = input.toString(),
body = init?.body,
method = init?.method;
if (typeof body == 'string') {
const proxy = new FetcherFetchProxy({
host,
name,
payload: { path, body, method },
});
const responseBody = await proxy.post<null>();
return new Response(responseBody);
}
throw new Error('Method not implemented.');
}
connect(
address: string | SocketAddress,
options?: SocketOptions | undefined
): Socket {
throw new Error('Method not implemented.');
}
}

export { FetcherProxyHolder };
20 changes: 13 additions & 7 deletions src/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { createMimeMessage } from 'mimetext';
import type { ErrorResult, PostData, SuccessResult } from './data';
import { ProxyFactory } from './factory';
import { D1DatabaseProxyHolder } from './proxies/d1_database/proxy_holder';
import { FetcherProxyHolder } from './proxies/fetcher/proxy_holder';
import { SendEmailProxy } from './proxies/send_email/proxy';

const json = <T>(data: T) => {
Expand Down Expand Up @@ -78,11 +79,7 @@ const json = <T>(data: T) => {
msg.setSubject(subject);
msg.addMessage({ contentType, data });
const { EmailMessage } = await import('cloudflare:email'),
message = new EmailMessage(
'[email protected]',
'[email protected]',
msg.asRaw()
);
message = new EmailMessage(addr, recipent, msg.asRaw());
await seb.send(message);
} else {
const proxy = new SendEmailProxy({
Expand All @@ -92,6 +89,15 @@ const json = <T>(data: T) => {
});
await proxy.post();
}
};
},
createServiceBinding = (
name: string,
options?: { hostname?: string }
): Fetcher =>
new FetcherProxyHolder({
host: options?.hostname ?? 'http://localhost:8787',
name,
payload: {},
});

export { createD1, createWorker, sendEmail };
export { createD1, createServiceBinding, createWorker, sendEmail };

0 comments on commit 0190115

Please sign in to comment.