Skip to content

Commit e2ecf6f

Browse files
committed
Split up code into single-object files
1 parent ea7820c commit e2ecf6f

File tree

5 files changed

+76
-73
lines changed

5 files changed

+76
-73
lines changed

index.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1-
import Client from "./lib/client.js";
2-
const replicate = new Client({});
1+
import ReplicateClient from "./lib/ReplicateClient.js";
2+
3+
const replicate = new ReplicateClient({});
4+
35
export default replicate;

lib/Prediction.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
export default class Prediction {
2+
static fromJSON(json) {
3+
const prediction = new Prediction();
4+
Object.assign(prediction, json);
5+
// TODO: make prediction.version a Version object
6+
return prediction;
7+
}
8+
}

lib/PredictionCollection.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import Prediction from "./Prediction.js";
2+
3+
export default class PredictionCollection {
4+
constructor({ client }) {
5+
this.client = client;
6+
}
7+
8+
async create({ version, input }) {
9+
const response = await this.client._request({
10+
method: "POST",
11+
path: `/v1/predictions`,
12+
body: {
13+
version,
14+
input,
15+
},
16+
});
17+
return Prediction.fromJSON(response);
18+
}
19+
20+
async get({ id }) {
21+
const response = await this.client._request({
22+
method: "GET",
23+
path: `/v1/predictions/${id}`,
24+
});
25+
return Prediction.fromJSON(response);
26+
}
27+
28+
async list() {
29+
const response = await this.client._request({
30+
method: "GET",
31+
path: `/v1/predictions`,
32+
});
33+
// TODO pagination
34+
return response.results.map((prediction) =>
35+
Prediction.fromJSON(prediction)
36+
);
37+
}
38+
}

lib/ReplicateClient.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import fetch from "node-fetch";
2+
import pkg from "../package.json" assert { type: "json" };
3+
import PredictionCollection from "./PredictionCollection.js";
4+
5+
export default class ReplicateClient {
6+
constructor({ token }) {
7+
this.token = token || process.env.REPLICATE_API_TOKEN;
8+
this.predictions = new PredictionCollection({ client: this });
9+
}
10+
11+
async _request({ method, path, body }) {
12+
const response = await fetch(`https://api.replicate.com${path}`, {
13+
method: method,
14+
headers: this._headers(),
15+
body: JSON.stringify(body),
16+
});
17+
return await response.json();
18+
}
19+
20+
_headers() {
21+
return {
22+
Authorization: `Token ${this.token}`,
23+
"User-Agent": `replicate-js@${pkg.version}`,
24+
};
25+
}
26+
}

lib/client.js

Lines changed: 0 additions & 71 deletions
This file was deleted.

0 commit comments

Comments
 (0)